diff --git a/testingx/testdata/valid-file.txt b/testingx/testdata/valid-file.txt new file mode 100644 index 0000000..1910281 --- /dev/null +++ b/testingx/testdata/valid-file.txt @@ -0,0 +1 @@ +foo \ No newline at end of file diff --git a/testingx/testingx.go b/testingx/testingx.go index c8997d8..8fd15b1 100644 --- a/testingx/testingx.go +++ b/testingx/testingx.go @@ -2,6 +2,7 @@ package testingx import ( "fmt" + "os" ) // FatalReporter defines the interface for reporting a fatal test. @@ -16,12 +17,15 @@ type FatalReporter interface { // a format string. // // The main purpose of this function is to turn the common pattern of: -// err := Func() -// if err != nil { -// t.Fatalf("Helpful message (error: %v)", err) -// } +// +// err := Func() +// if err != nil { +// t.Fatalf("Helpful message (error: %v)", err) +// } +// // into a simplified pattern of: -// Must(t, Func(), "Helpful message") +// +// Must(t, Func(), "Helpful message") // // This has the benefit of using fewer lines and verifying unit tests are // "correct by inspection". @@ -35,3 +39,11 @@ func Must(t FatalReporter, err error, prefix string, args ...interface{}) { t.Fatal(prefix + suffix) } } + +// MustReadFile will read the file under the input `path` and return the array +// of bytes. If it fails, it will call t.Fatal. +func MustReadFile(t FatalReporter, path string) []byte { + file, err := os.ReadFile(path) + Must(t, err, "") + return file +} diff --git a/testingx/testingx_test.go b/testingx/testingx_test.go index 314042d..978c4d2 100644 --- a/testingx/testingx_test.go +++ b/testingx/testingx_test.go @@ -1,6 +1,7 @@ package testingx import ( + "bytes" "errors" "testing" ) @@ -28,3 +29,24 @@ func TestMust(t *testing.T) { } }) } + +func TestMustReadFile_Success(t *testing.T) { + f := &fakeReporter{} + got := MustReadFile(f, "./testdata/valid-file.txt") + if f.called != 0 { + t.Fatal("MustReadFile() t.Fatal called for valid file") + } + + want := []byte("foo") + if !bytes.Equal(got, want) { + t.Fatalf("MustReadFile() got = %s, want = %s", string(got), string(want)) + } +} + +func TestMustReadFile_Error(t *testing.T) { + f := &fakeReporter{} + MustReadFile(f, "./testdata/invalid-file.txt") + if f.called != 1 { + t.Fatal("MustReadFile() t.Fatal NOT called for invalid file") + } +}