github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/os/stat_test.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package os_test 6 7 import ( 8 "io/fs" 9 "os" 10 "path/filepath" 11 "testing" 12 ) 13 14 // testStatAndLstat verifies that all os.Stat, os.Lstat os.File.Stat and os.Readdir work. 15 func testStatAndLstat(t *testing.T, path string, isLink bool, statCheck, lstatCheck func(*testing.T, string, fs.FileInfo)) { 16 // TODO: revert to upstream test once fstat and readdir are implemented 17 // test os.Stat 18 sfi, err := os.Stat(path) 19 if err != nil { 20 t.Error(err) 21 return 22 } 23 statCheck(t, path, sfi) 24 25 // test os.Lstat 26 lsfi, err := os.Lstat(path) 27 if err != nil { 28 t.Error(err) 29 return 30 } 31 lstatCheck(t, path, lsfi) 32 33 if isLink { 34 if os.SameFile(sfi, lsfi) { 35 t.Errorf("stat and lstat of %q should not be the same", path) 36 } 37 } else { 38 if !os.SameFile(sfi, lsfi) { 39 t.Errorf("stat and lstat of %q should be the same", path) 40 } 41 } 42 } 43 44 // testIsDir verifies that fi refers to directory. 45 func testIsDir(t *testing.T, path string, fi fs.FileInfo) { 46 t.Helper() 47 if !fi.IsDir() { 48 t.Errorf("%q should be a directory", path) 49 } 50 if fi.Mode()&fs.ModeSymlink != 0 { 51 t.Errorf("%q should not be a symlink", path) 52 } 53 } 54 55 // testIsFile verifies that fi refers to file. 56 func testIsFile(t *testing.T, path string, fi fs.FileInfo) { 57 t.Helper() 58 if fi.IsDir() { 59 t.Errorf("%q should not be a directory", path) 60 } 61 if fi.Mode()&fs.ModeSymlink != 0 { 62 t.Errorf("%q should not be a symlink", path) 63 } 64 } 65 66 func testDirStats(t *testing.T, path string) { 67 testStatAndLstat(t, path, false, testIsDir, testIsDir) 68 } 69 70 func testFileStats(t *testing.T, path string) { 71 testStatAndLstat(t, path, false, testIsFile, testIsFile) 72 } 73 74 func TestDirAndSymlinkStats(t *testing.T) { 75 // TODO: revert to upstream test once symlinks and t.TempDir are implemented 76 tmpdir := os.TempDir() 77 dir := filepath.Join(tmpdir, "dir") 78 os.Remove(dir) 79 if err := os.Mkdir(dir, 0777); err != nil { 80 t.Fatal(err) 81 return 82 } 83 testDirStats(t, dir) 84 85 } 86 87 func TestFileAndSymlinkStats(t *testing.T) { 88 // TODO: revert to upstream test once symlinks and t.TempDir are implemented 89 tmpdir := os.TempDir() 90 file := filepath.Join(tmpdir, "file") 91 if err := os.WriteFile(file, []byte("abcdefg"), 0644); err != nil { 92 t.Fatal(err) 93 return 94 } 95 testFileStats(t, file) 96 }