Skip to content

Commit

Permalink
Add MustReadFile utility (#162)
Browse files Browse the repository at this point in the history
* Add MustReadFile utility

* Comment
  • Loading branch information
cristinaleonr authored Mar 1, 2023
1 parent 999e57b commit 740dcf0
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
1 change: 1 addition & 0 deletions testingx/testdata/valid-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
foo
22 changes: 17 additions & 5 deletions testingx/testingx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package testingx

import (
"fmt"
"os"
)

// FatalReporter defines the interface for reporting a fatal test.
Expand All @@ -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".
Expand All @@ -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
}
22 changes: 22 additions & 0 deletions testingx/testingx_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package testingx

import (
"bytes"
"errors"
"testing"
)
Expand Down Expand Up @@ -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")
}
}

0 comments on commit 740dcf0

Please sign in to comment.