Skip to content

Commit

Permalink
adds some unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Adrian Cole <adrian@tetrate.io>
  • Loading branch information
Adrian Cole committed Mar 23, 2022
1 parent cf58985 commit 7281220
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/wasi/wasi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2224,7 +2224,7 @@ func createFile(t *testing.T, pathName string, data []byte) (fs.File, fs.FS) {
return f, mapFS
}

// configureWriteableFile uses real files when io.Writer tests are needed.
// createWriteableFile uses real files when io.Writer tests are needed.
func createWriteableFile(t *testing.T, tmpDir string, pathName string, data []byte) (fs.File, fs.FS) {
require.NotNil(t, data)
absolutePath := path.Join(tmpDir, pathName)
Expand Down
56 changes: 56 additions & 0 deletions internal/wasm/sys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package internalwasm
import (
"bytes"
"io"
"io/fs"
"os"
"path"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -147,3 +150,56 @@ func TestNewSysContext_Environ(t *testing.T) {
})
}
}

func TestSysContext_Close(t *testing.T) {
t.Run("no files", func(t *testing.T) {
sys := DefaultSysContext()
require.NoError(t, sys.Close())
})

t.Run("open files", func(t *testing.T) {
tempDir := t.TempDir()
pathName := "test"
file, testFS := createWriteableFile(t, tempDir, pathName, make([]byte, 0))

sys, err := NewSysContext(
0, // max
nil, // args
nil, // environ
nil, // stdin
nil, // stdout
nil, // stderr
map[uint32]*FileEntry{ // openedFiles
3: {Path: ".", FS: testFS},
4: {Path: path.Join(".", pathName), File: file, FS: testFS},
},
)
require.NoError(t, err)

// Closing should delete the file descriptors after closing the files.
require.NoError(t, sys.Close())
require.Empty(t, sys.openedFiles)

// Verify it was actually closed, by trying to close it again.
err = file.(*os.File).Close()
require.Contains(t, err.Error(), "file already closed")

// No problem closing config again because the descriptors were removed, so they won't be called again.
require.NoError(t, sys.Close())
})

// TODO: fs but never used (ex file == nil)
// TODO: externally closed
}

// createWriteableFile uses real files when io.Writer tests are needed.
func createWriteableFile(t *testing.T, tmpDir string, pathName string, data []byte) (fs.File, fs.FS) {
require.NotNil(t, data)
absolutePath := path.Join(tmpDir, pathName)
require.NoError(t, os.WriteFile(absolutePath, data, 0o600))

// open the file for writing in a custom way until #390
f, err := os.OpenFile(absolutePath, os.O_RDWR, 0o600)
require.NoError(t, err)
return f, os.DirFS(tmpDir)
}

0 comments on commit 7281220

Please sign in to comment.