A lightweight test helper package
0

Configure Feed

Select the types of activity you want to include in your feed.

Add a test.File function for comparing expected file contents (#12)

* Add a test.File function for comparing expected file contents

* Normalise line endings in test.File

* Fix doc

* Fix doc 2

authored by

Tom Fleet and committed by
GitHub
(Nov 5, 2023, 1:22 PM UTC) 13cf44ef 0986fffe

+27
+24
test.go
··· 3 3 package test 4 4 5 5 import ( 6 + "bytes" 6 7 "fmt" 7 8 "os" 8 9 "path/filepath" ··· 171 172 } 172 173 173 174 return filepath.Join(cwd, "testdata") 175 + } 176 + 177 + // File fails if the contents of the given file do not match want. 178 + // 179 + // It takes the name of a file (relative to $CWD/testdata) and the contents to compare. 180 + // 181 + // If the contents differ, the test will fail with output equivalent to test.Diff. 182 + // 183 + // Files with differing line endings (e.g windows CR LF \r\n vs unix LF \n) will be normalised to 184 + // \n prior to comparison so this function will behave identically across multiple platforms. 185 + // 186 + // test.File(t, "expected.txt", "hello\n") 187 + func File(t testing.TB, file, want string) { 188 + t.Helper() 189 + file = filepath.Join(Data(t), file) 190 + contents, err := os.ReadFile(file) 191 + if err != nil { 192 + t.Fatalf("could not read %s: %v", file, err) 193 + } 194 + 195 + contents = bytes.ReplaceAll(contents, []byte("\r\n"), []byte("\n")) 196 + 197 + Diff(t, string(contents), want) 174 198 }
+2
test_test.go
··· 92 92 func(tb testing.TB) { test.DeepEqual(tb, []string{"hello"}, []string{"hello"}) }, 93 93 func(tb testing.TB) { test.WantErr(tb, errors.New("uh oh"), true) }, 94 94 func(tb testing.TB) { test.WantErr(tb, nilErr(), false) }, 95 + func(tb testing.TB) { test.File(tb, "file.txt", "hello\n") }, 95 96 } 96 97 97 98 for _, fn := range passFns { ··· 165 166 func(tb testing.TB) { test.DeepEqual(tb, []string{"hello"}, []string{"world"}) }, 166 167 func(tb testing.TB) { test.WantErr(tb, errors.New("uh oh"), false) }, 167 168 func(tb testing.TB) { test.WantErr(tb, nilErr(), true) }, 169 + func(tb testing.TB) { test.File(tb, "file.txt", "wrong\n") }, 168 170 } 169 171 170 172 for _, fn := range failFns {
+1
testdata/file.txt
··· 1 + hello