github.com/jmigpin/editor@v1.6.0/core/fswatcher/watcher_test.go (about)

     1  package fswatcher
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"math/rand"
     7  	"os"
     8  	"testing"
     9  	"time"
    10  )
    11  
    12  //----------
    13  
    14  func tmpDir() string {
    15  	name, err := ioutil.TempDir("", "watcher_test")
    16  	if err != nil {
    17  		panic(err)
    18  	}
    19  	return name
    20  }
    21  
    22  func mustMkdirAll(t *testing.T, name string) {
    23  	err := os.MkdirAll(name, 0755)
    24  	if err != nil {
    25  		t.Fatal(err)
    26  	}
    27  }
    28  
    29  func mustRemoveAll(t *testing.T, name string) {
    30  	t.Helper()
    31  	if err := os.RemoveAll(name); err != nil {
    32  		t.Fatal(err)
    33  	}
    34  }
    35  
    36  func mustRenameFile(t *testing.T, name, name2 string) {
    37  	t.Helper()
    38  	if err := os.Rename(name, name2); err != nil {
    39  		t.Fatal(err)
    40  	}
    41  }
    42  
    43  func mustCreateFile(t *testing.T, name string) {
    44  	t.Helper()
    45  	f, err := os.OpenFile(name, os.O_CREATE, 0644)
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  	if err := f.Close(); err != nil {
    50  		t.Fatal(err)
    51  	}
    52  }
    53  
    54  func mustWriteFile(t *testing.T, name string) {
    55  	t.Helper()
    56  	f, err := os.OpenFile(name, os.O_WRONLY, 0644)
    57  	if err != nil {
    58  		t.Fatal(err)
    59  	}
    60  	defer func() {
    61  		if err := f.Close(); err != nil {
    62  			t.Fatal(err)
    63  		}
    64  	}()
    65  
    66  	data := []byte(fmt.Sprintf("%v", rand.Int()))
    67  	n, err := f.Write(data)
    68  	if err != nil {
    69  		t.Fatal(err)
    70  	}
    71  	if n < len(data) {
    72  		t.Fatal("short write")
    73  	}
    74  }
    75  
    76  //----------
    77  
    78  func mustAddWatch(t *testing.T, w Watcher, name string) {
    79  	t.Helper()
    80  	if err := w.Add(name); err != nil {
    81  		t.Fatal(err)
    82  	}
    83  }
    84  
    85  func mustRemoveWatch(t *testing.T, w Watcher, name string) {
    86  	t.Helper()
    87  	if err := w.Remove(name); err != nil {
    88  		t.Fatal(err)
    89  	}
    90  }
    91  
    92  //----------
    93  
    94  func readEvent(t *testing.T, w Watcher, failOnTimeout bool, fn func(*Event) bool) {
    95  	t.Helper()
    96  	tick := time.NewTicker(3000 * time.Millisecond)
    97  	defer tick.Stop()
    98  	select {
    99  	case <-tick.C:
   100  		if failOnTimeout {
   101  			t.Fatal("event timeout")
   102  		}
   103  	case ev := <-w.Events():
   104  		if err, ok := ev.(error); ok {
   105  			t.Fatal(err)
   106  		} else if !fn(ev.(*Event)) {
   107  			t.Fatal(ev)
   108  		}
   109  	}
   110  }