github.com/deadlysurgeon/weather@v0.0.0-20240402201029-3925d9f784b1/settings/settings_test.go (about) 1 package settings 2 3 import ( 4 "os" 5 "strings" 6 "testing" 7 ) 8 9 func TestSettings(t *testing.T) { 10 wd, err := os.Getwd() 11 if err != nil { 12 t.Fatalf("Failed to get current testing directory: %v", err) 13 } 14 defer os.Chdir(wd) // Restore WD 15 16 type TestObj struct { 17 Hello string 18 } 19 20 for name, test := range map[string]struct { 21 Prelude func(t *testing.T) 22 Compare func(t *testing.T, to TestObj) 23 Directory string 24 ErrorLike string 25 }{ 26 "basic file": { 27 Prelude: func(t *testing.T) {}, 28 Compare: func(t *testing.T, to TestObj) { 29 if to.Hello != "World" { 30 t.Fatalf("Expected \"World\" got \"%v\"", to.Hello) 31 } 32 }, 33 Directory: "testing/basic", 34 }, 35 "bad file": { 36 Prelude: func(t *testing.T) {}, 37 Compare: func(t *testing.T, to TestObj) {}, 38 Directory: "testing/badfile", 39 ErrorLike: "unexpected character \"!\"", 40 }, 41 "no file": { 42 Prelude: func(t *testing.T) { 43 if err := os.Setenv("HELLO", "No File"); err != nil { 44 t.Fatalf("Failed to set env for test: %v", err) 45 } 46 }, 47 Compare: func(t *testing.T, to TestObj) { 48 if to.Hello != "No File" { 49 t.Fatalf("Expected \"No File\" got \"%v\"", to.Hello) 50 } 51 }, 52 Directory: "testing/nofile", 53 }, 54 } { 55 test := test 56 t.Run(name, func(t *testing.T) { 57 if err := os.Chdir(wd); err != nil { 58 t.Fatalf("Failed to reset WD: %v", err) 59 } 60 61 if test.Directory != "" { 62 if err := os.Chdir(test.Directory); err != nil { 63 t.Fatalf("Failed to set Test Directory: %v", err) 64 } 65 } 66 67 test.Prelude(t) 68 conf, err := Process[TestObj]() 69 if (test.ErrorLike != "") != (err != nil) { 70 t.Fatalf("Expect Error %v got %v", (test.ErrorLike != ""), err) 71 } 72 if test.ErrorLike != "" { 73 if !strings.Contains(err.Error(), test.ErrorLike) { 74 t.Fatalf("Expected error to contain \"%v\" but it didn't. Error: %v", test.ErrorLike, err) 75 } 76 return 77 } 78 test.Compare(t, conf) 79 }) 80 } 81 }