1 package fs_test
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7 "testing"
8
9 "gotest.tools/v3/assert"
10 "gotest.tools/v3/fs"
11 "gotest.tools/v3/internal/source"
12 "gotest.tools/v3/skip"
13 )
14
15 func TestNewDirWithOpsAndManifestEqual(t *testing.T) {
16 var userOps []fs.PathOp
17 if os.Geteuid() == 0 {
18 userOps = append(userOps, fs.AsUser(1001, 1002))
19 }
20
21 ops := []fs.PathOp{
22 fs.WithFile("file1", "contenta", fs.WithMode(0400)),
23 fs.WithFile("file2", "", fs.WithBytes([]byte{0, 1, 2})),
24 fs.WithFile("file5", "", userOps...),
25 fs.WithSymlink("link1", "file1"),
26 fs.WithDir("sub",
27 fs.WithFiles(map[string]string{
28 "file3": "contentb",
29 "file4": "contentc",
30 }),
31 fs.WithMode(0705),
32 ),
33 }
34
35 dir := fs.NewDir(t, "test-all", ops...)
36 defer dir.Remove()
37
38 manifestOps := append(
39 ops[:3],
40 fs.WithSymlink("link1", dir.Join("file1")),
41 ops[4],
42 )
43 assert.Assert(t, fs.Equal(dir.Path(), fs.Expected(t, manifestOps...)))
44 }
45
46 func TestNewFile(t *testing.T) {
47 t.Run("with test name", func(t *testing.T) {
48 tmpFile := fs.NewFile(t, t.Name())
49 _, err := os.Stat(tmpFile.Path())
50 assert.NilError(t, err)
51
52 tmpFile.Remove()
53 _, err = os.Stat(tmpFile.Path())
54 assert.ErrorIs(t, err, os.ErrNotExist)
55 })
56
57 t.Run(`with \ in name`, func(t *testing.T) {
58 tmpFile := fs.NewFile(t, `foo\thing`)
59 _, err := os.Stat(tmpFile.Path())
60 assert.NilError(t, err)
61
62 tmpFile.Remove()
63 _, err = os.Stat(tmpFile.Path())
64 assert.ErrorIs(t, err, os.ErrNotExist)
65 })
66 }
67
68 func TestNewFile_IntegrationWithCleanup(t *testing.T) {
69 skip.If(t, source.GoVersionLessThan(1, 14))
70 var tmpFile *fs.File
71 t.Run("cleanup in subtest", func(t *testing.T) {
72 tmpFile = fs.NewFile(t, t.Name())
73 _, err := os.Stat(tmpFile.Path())
74 assert.NilError(t, err)
75 })
76
77 t.Run("file has been removed", func(t *testing.T) {
78 _, err := os.Stat(tmpFile.Path())
79 assert.ErrorIs(t, err, os.ErrNotExist)
80 })
81 }
82
83 func TestNewDir_IntegrationWithCleanup(t *testing.T) {
84 skip.If(t, source.GoVersionLessThan(1, 14))
85 var tmpFile *fs.Dir
86 t.Run("cleanup in subtest", func(t *testing.T) {
87 tmpFile = fs.NewDir(t, t.Name())
88 _, err := os.Stat(tmpFile.Path())
89 assert.NilError(t, err)
90 })
91
92 t.Run("dir has been removed", func(t *testing.T) {
93 _, err := os.Stat(tmpFile.Path())
94 assert.ErrorIs(t, err, os.ErrNotExist)
95 })
96 }
97
98 func TestDirFromPath(t *testing.T) {
99 tmpdir := t.TempDir()
100
101 dir := fs.DirFromPath(t, tmpdir, fs.WithFile("newfile", ""))
102
103 _, err := os.Stat(dir.Join("newfile"))
104 assert.NilError(t, err)
105
106 assert.Equal(t, dir.Path(), tmpdir)
107 assert.Equal(t, dir.Join("newfile"), filepath.Join(tmpdir, "newfile"))
108
109 dir.Remove()
110
111 _, err = os.Stat(tmpdir)
112 assert.Assert(t, errors.Is(err, os.ErrNotExist))
113 }
114
View as plain text