github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/osutil/osutil_test.go (about) 1 // Copyright 2017 syzkaller project authors. All rights reserved. 2 // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. 3 4 package osutil 5 6 import ( 7 "fmt" 8 "os" 9 "path/filepath" 10 "strings" 11 "testing" 12 "time" 13 ) 14 15 func TestIsExist(t *testing.T) { 16 if f := os.Args[0]; !IsExist(f) { 17 t.Fatalf("executable %v does not exist", f) 18 } 19 if f := os.Args[0] + "-foo-bar-buz"; IsExist(f) { 20 t.Fatalf("file %v exists", f) 21 } 22 } 23 24 func TestCopyFiles(t *testing.T) { 25 type Test struct { 26 files []string 27 patterns map[string]bool 28 err string 29 } 30 tests := []Test{ 31 { 32 files: []string{ 33 "foo", 34 "bar", 35 "baz/foo", 36 "baz/bar", 37 }, 38 patterns: map[string]bool{ 39 "foo": true, 40 "bar": false, 41 "qux": false, 42 "baz/foo": true, 43 "baz/bar": false, 44 }, 45 }, 46 { 47 files: []string{ 48 "foo", 49 }, 50 patterns: map[string]bool{ 51 "bar": true, 52 }, 53 err: "file bar does not exist", 54 }, 55 { 56 files: []string{ 57 "baz/foo", 58 "baz/bar", 59 }, 60 patterns: map[string]bool{ 61 "baz/*": true, 62 }, 63 }, 64 { 65 files: []string{ 66 "qux/foo/foo", 67 "qux/foo/bar", 68 "qux/bar/foo", 69 "qux/bar/bar", 70 }, 71 patterns: map[string]bool{ 72 "qux/*/*": false, 73 }, 74 }, 75 } 76 for _, link := range []bool{false, true} { 77 fn, fnName := CopyFiles, "CopyFiles" 78 if link { 79 fn, fnName = LinkFiles, "LinkFiles" 80 } 81 t.Run(fnName, func(t *testing.T) { 82 for i, test := range tests { 83 t.Run(fmt.Sprint(i), func(t *testing.T) { 84 dir := t.TempDir() 85 src := filepath.Join(dir, "src") 86 dst := filepath.Join(dir, "dst") 87 for _, file := range test.files { 88 file = filepath.Join(src, filepath.FromSlash(file)) 89 if err := MkdirAll(filepath.Dir(file)); err != nil { 90 t.Fatal(err) 91 } 92 if err := WriteFile(file, []byte{'a'}); err != nil { 93 t.Fatal(err) 94 } 95 } 96 if err := fn(src, dst, test.patterns); err != nil { 97 if test.err != "" { 98 if strings.Contains(err.Error(), test.err) { 99 return 100 } 101 t.Fatalf("got err %q, want %q", err, test.err) 102 } 103 t.Fatal(err) 104 } else if test.err != "" { 105 t.Fatalf("got no err, want %q", test.err) 106 } 107 if err := os.RemoveAll(src); err != nil { 108 t.Fatal(err) 109 } 110 for _, file := range test.files { 111 if !IsExist(filepath.Join(dst, filepath.FromSlash(file))) { 112 t.Fatalf("%v does not exist in dst", file) 113 } 114 } 115 if !FilesExist(dst, test.patterns) { 116 t.Fatalf("dst files don't exist after copy") 117 } 118 }) 119 } 120 }) 121 } 122 } 123 124 func TestMonotonicNano(t *testing.T) { 125 start := MonotonicNano() 126 time.Sleep(100 * time.Millisecond) 127 diff := MonotonicNano() - start 128 if diff <= 0 || diff > 10*time.Second { 129 t.Fatalf("diff %v", diff) 130 } 131 }