github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/mods/file/file_test.go (about) 1 package file 2 3 import ( 4 "os" 5 "testing" 6 7 "github.com/markusbkk/elvish/pkg/eval" 8 "github.com/markusbkk/elvish/pkg/eval/errs" 9 . "github.com/markusbkk/elvish/pkg/eval/evaltest" 10 "github.com/markusbkk/elvish/pkg/testutil" 11 ) 12 13 // A number that exceeds the range of int64 14 const z = "100000000000000000000" 15 16 func TestFile(t *testing.T) { 17 setup := func(ev *eval.Evaler) { 18 ev.ExtendGlobal(eval.BuildNs().AddNs("file", Ns)) 19 } 20 testutil.InTempDir(t) 21 22 TestWithSetup(t, setup, 23 That(` 24 echo haha > out3 25 var f = (file:open out3) 26 slurp < $f 27 file:close $f 28 `).Puts("haha\n"), 29 30 That(` 31 var p = (file:pipe) 32 echo haha > $p 33 file:close $p[w] 34 slurp < $p 35 file:close $p[r] 36 `).Puts("haha\n"), 37 38 That(` 39 var p = (file:pipe) 40 echo Legolas > $p 41 file:close $p[r] 42 slurp < $p 43 `).Throws(ErrorWithType(&os.PathError{})), 44 45 // Verify that input redirection from a closed pipe throws an exception. That exception is a 46 // Go stdlib error whose stringified form looks something like "read |0: file already 47 // closed". 48 That(`var p = (file:pipe)`, `echo Legolas > $p`, `file:close $p[r]`, 49 `slurp < $p`).Throws(ErrorWithType(&os.PathError{})), 50 51 // Side effect checked below 52 That("echo > file100", "file:truncate file100 100").DoesNothing(), 53 54 // Should also test the case where the argument doesn't fit in an int 55 // but does in a *big.Int, but this could consume too much disk 56 57 That("file:truncate bad -1").Throws(errs.OutOfRange{ 58 What: "size argument to file:truncate", 59 ValidLow: "0", ValidHigh: "2^64-1", Actual: "-1", 60 }), 61 62 That("file:truncate bad "+z).Throws(errs.OutOfRange{ 63 What: "size argument to file:truncate", 64 ValidLow: "0", ValidHigh: "2^64-1", Actual: z, 65 }), 66 67 That("file:truncate bad 1.5").Throws(errs.BadValue{ 68 What: "size argument to file:truncate", 69 Valid: "integer", Actual: "non-integer", 70 }), 71 ) 72 73 fi, err := os.Stat("file100") 74 if err != nil { 75 t.Errorf("stat file100: %v", err) 76 } 77 if size := fi.Size(); size != 100 { 78 t.Errorf("got file100 size %v, want 100", size) 79 } 80 }