gitlab.com/xtgo/livefile@v0.0.2/writes_test.go (about)

     1  package livefile
     2  
     3  import (
     4  	"os"
     5  	"regexp"
     6  	"testing"
     7  )
     8  
     9  func Test_createTemp(t *testing.T) {
    10  	regex := regexp.MustCompile(`^/path/to/dir/some-file~[0-9a-f]{16}$`)
    11  
    12  	const dir = "/path/to/dir"
    13  	const pre = "some-file~"
    14  
    15  	tries := 5
    16  	var lastPath string
    17  
    18  	path, err := createTemp(dir, pre, func(path string) error {
    19  		if path == lastPath {
    20  			msg := "createTemp used same path twice:\nprev: %q\ncurr: %q"
    21  			t.Fatalf(msg, lastPath, path)
    22  		}
    23  
    24  		lastPath = path
    25  
    26  		if !regex.MatchString(path) {
    27  			msg := "createTemp produced non-conforming path: %q"
    28  			t.Fatalf(msg, path)
    29  		}
    30  
    31  		if tries == 0 {
    32  			return nil
    33  		}
    34  
    35  		tries--
    36  
    37  		return os.ErrExist
    38  	})
    39  
    40  	if err != nil {
    41  		msg := "createTemp(...) = %q [error], want nil"
    42  		t.Fatalf(msg, err)
    43  	}
    44  
    45  	if path != lastPath {
    46  		msg := "createTemp(...) = %q, want: %q"
    47  		t.Fatalf(msg, path, lastPath)
    48  	}
    49  
    50  	if tries != 0 {
    51  		msg := "createTemp took fewer than expected tries (got %d, want 0)"
    52  		t.Fatalf(msg, tries)
    53  	}
    54  }