wa-lang.org/wazero@v1.0.2/internal/sys/fs_test.go (about) 1 package sys 2 3 import ( 4 "context" 5 "errors" 6 "testing" 7 8 testfs "wa-lang.org/wazero/internal/testing/fs" 9 "wa-lang.org/wazero/internal/testing/require" 10 ) 11 12 // testCtx is an arbitrary, non-default context. Non-nil also prevents linter errors. 13 var testCtx = context.WithValue(context.Background(), struct{}{}, "arbitrary") 14 15 func TestEmptyFS(t *testing.T) { 16 testFS := EmptyFS 17 18 t.Run("validates path", func(t *testing.T) { 19 f, err := testFS.Open("/foo.txt") 20 require.Nil(t, f) 21 require.EqualError(t, err, "open /foo.txt: invalid argument") 22 }) 23 24 t.Run("path not found", func(t *testing.T) { 25 f, err := testFS.Open("foo.txt") 26 require.Nil(t, f) 27 require.EqualError(t, err, "open foo.txt: file does not exist") 28 }) 29 } 30 31 func TestEmptyFSContext(t *testing.T) { 32 testFS := emptyFSContext 33 expected := &FSContext{ 34 fs: EmptyFS, 35 openedFiles: map[uint32]*FileEntry{}, 36 lastFD: 2, 37 } 38 39 t.Run("OpenFile doesn't affect state", func(t *testing.T) { 40 fd, err := testFS.OpenFile(testCtx, "foo.txt") 41 require.Zero(t, fd) 42 require.EqualError(t, err, "open foo.txt: file does not exist") 43 44 // Ensure this didn't modify state 45 require.Equal(t, expected, testFS) 46 }) 47 48 t.Run("Close doesn't affect state", func(t *testing.T) { 49 err := testFS.Close(testCtx) 50 require.NoError(t, err) 51 52 // Ensure this didn't modify state 53 require.Equal(t, expected, testFS) 54 }) 55 } 56 57 func TestContext_Close(t *testing.T) { 58 fsc := NewFSContext(testfs.FS{"foo": &testfs.File{}}) 59 _, err := fsc.OpenFile(testCtx, "/foo") 60 require.NoError(t, err) 61 62 // Verify base case 63 require.True(t, len(fsc.openedFiles) > 0, "fsc.openedFiles was empty") 64 65 // Closing should not err. 66 require.NoError(t, fsc.Close(testCtx)) 67 68 // Verify our intended side-effect 69 require.Zero(t, len(fsc.openedFiles), "expected no opened files") 70 71 // Verify no error closing again. 72 require.NoError(t, fsc.Close(testCtx)) 73 } 74 75 func TestContext_Close_Error(t *testing.T) { 76 file := &testfs.File{CloseErr: errors.New("error closing")} 77 fsc := NewFSContext(testfs.FS{"foo": file}) 78 _, err := fsc.OpenFile(testCtx, "/foo") 79 require.NoError(t, err) 80 81 require.EqualError(t, fsc.Close(testCtx), "error closing") 82 83 // Paths should clear even under error 84 require.Zero(t, len(fsc.openedFiles), "expected no opened files") 85 }