github.com/DominikUrban/viper@v0.0.0-20220730150717-aaf74638bd32/fs_test.go (about) 1 //go:build go1.16 && finder 2 // +build go1.16,finder 3 4 package viper 5 6 import ( 7 "io/fs" 8 "testing" 9 "testing/fstest" 10 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestFinder(t *testing.T) { 16 t.Parallel() 17 18 fsys := fstest.MapFS{ 19 "home/user/.config": &fstest.MapFile{}, 20 "home/user/config.json": &fstest.MapFile{}, 21 "home/user/config.yaml": &fstest.MapFile{}, 22 "home/user/data.json": &fstest.MapFile{}, 23 "etc/config/.config": &fstest.MapFile{}, 24 "etc/config/a_random_file.txt": &fstest.MapFile{}, 25 "etc/config/config.json": &fstest.MapFile{}, 26 "etc/config/config.yaml": &fstest.MapFile{}, 27 "etc/config/config.xml": &fstest.MapFile{}, 28 } 29 30 testCases := []struct { 31 name string 32 fsys func() fs.FS 33 finder finder 34 result string 35 }{ 36 { 37 name: "find file", 38 fsys: func() fs.FS { return fsys }, 39 finder: finder{ 40 paths: []string{"etc/config"}, 41 fileNames: []string{"config"}, 42 extensions: []string{"json"}, 43 }, 44 result: "etc/config/config.json", 45 }, 46 { 47 name: "file not found", 48 fsys: func() fs.FS { return fsys }, 49 finder: finder{ 50 paths: []string{"var/config"}, 51 fileNames: []string{"config"}, 52 extensions: []string{"json"}, 53 }, 54 result: "", 55 }, 56 { 57 name: "empty search params", 58 fsys: func() fs.FS { return fsys }, 59 finder: finder{}, 60 result: "", 61 }, 62 { 63 name: "precedence", 64 fsys: func() fs.FS { return fsys }, 65 finder: finder{ 66 paths: []string{"var/config", "home/user", "etc/config"}, 67 fileNames: []string{"aconfig", "config"}, 68 extensions: []string{"zml", "xml", "json"}, 69 }, 70 result: "home/user/config.json", 71 }, 72 { 73 name: "without extension", 74 fsys: func() fs.FS { return fsys }, 75 finder: finder{ 76 paths: []string{"var/config", "home/user", "etc/config"}, 77 fileNames: []string{".config"}, 78 extensions: []string{"zml", "xml", "json"}, 79 80 withoutExtension: true, 81 }, 82 result: "home/user/.config", 83 }, 84 } 85 86 for _, testCase := range testCases { 87 testCase := testCase 88 89 t.Run(testCase.name, func(t *testing.T) { 90 t.Parallel() 91 92 fsys := testCase.fsys() 93 94 result, err := testCase.finder.Find(fsys) 95 require.NoError(t, err) 96 97 assert.Equal(t, testCase.result, result) 98 }) 99 } 100 }