github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/find/find_test.go (about) 1 // Copyright 2015-2017 the u-root 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 find 6 7 import ( 8 "context" 9 "os" 10 "path/filepath" 11 "reflect" 12 "strings" 13 "syscall" 14 "testing" 15 ) 16 17 func TestSimple(t *testing.T) { 18 type tests struct { 19 name string 20 opts Set 21 names []string 22 } 23 24 testCases := []tests{ 25 { 26 name: "basic find", 27 opts: nil, 28 names: []string{ 29 "", 30 "/root", 31 "/root/xyz", 32 "/root/xyz/0777", 33 "/root/xyz/file", 34 }, 35 }, 36 { 37 name: "just a dir", 38 opts: WithModeMatch(os.ModeDir, os.ModeDir), 39 names: []string{ 40 "", 41 "/root", 42 "/root/xyz", 43 }, 44 }, 45 { 46 name: "just a file", 47 opts: WithModeMatch(0, os.ModeType), 48 names: []string{ 49 "/root/xyz/0777", 50 "/root/xyz/file", 51 }, 52 }, 53 { 54 name: "file by mode", 55 opts: WithModeMatch(0o444, os.ModePerm), 56 names: []string{"/root/xyz/0777"}, 57 }, 58 { 59 name: "file by name", 60 opts: WithFilenameMatch("*file"), 61 names: []string{"/root/xyz/file"}, 62 }, 63 } 64 d := t.TempDir() 65 66 // Make sure files are actually created with the permissions we ask for. 67 syscall.Umask(0) 68 if err := os.MkdirAll(filepath.Join(d, "root/xyz"), 0o775); err != nil { 69 t.Fatal(err) 70 } 71 if err := os.WriteFile(filepath.Join(d, "root/xyz/file"), nil, 0o664); err != nil { 72 t.Fatal(err) 73 } 74 if err := os.WriteFile(filepath.Join(d, "root/xyz/0777"), nil, 0o444); err != nil { 75 t.Fatal(err) 76 } 77 78 for _, tc := range testCases { 79 t.Run(tc.name, func(t *testing.T) { 80 ctx := context.Background() 81 files := Find(ctx, WithRoot(d), tc.opts) 82 83 var names []string 84 for o := range files { 85 if o.Err != nil { 86 t.Errorf("%v: got %v, want nil", o.Name, o.Err) 87 } 88 names = append(names, strings.TrimPrefix(o.Name, d)) 89 } 90 91 if len(names) != len(tc.names) { 92 t.Errorf("Find output: got %d bytes, want %d bytes", len(names), len(tc.names)) 93 } 94 if !reflect.DeepEqual(names, tc.names) { 95 t.Errorf("Find output: got %v, want %v", names, tc.names) 96 } 97 }) 98 } 99 }