From 3fb96b714a17389d381f2175860a33760c082ab1 Mon Sep 17 00:00:00 2001 From: Stephen Soltesz Date: Wed, 9 Sep 2020 15:22:23 -0400 Subject: [PATCH] Add testingx package (#127) --- testingx/testingx.go | 37 +++++++++++++++++++++++++++++++++++++ testingx/testingx_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 testingx/testingx.go create mode 100644 testingx/testingx_test.go diff --git a/testingx/testingx.go b/testingx/testingx.go new file mode 100644 index 0000000..c8997d8 --- /dev/null +++ b/testingx/testingx.go @@ -0,0 +1,37 @@ +package testingx + +import ( + "fmt" +) + +// FatalReporter defines the interface for reporting a fatal test. +type FatalReporter interface { + Fatal(args ...interface{}) + Helper() +} + +// Must allows the rtx.Must pattern within a unit test and will call t.Fatal if +// passed a non-nil error. The fatal message is specified as the prefix +// argument. If any further args are passed, then the prefix will be treated as +// 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) +// } +// into a simplified pattern of: +// Must(t, Func(), "Helpful message") +// +// This has the benefit of using fewer lines and verifying unit tests are +// "correct by inspection". +func Must(t FatalReporter, err error, prefix string, args ...interface{}) { + t.Helper() // Excludes this function from the line reported by t.Fatal. + if err != nil { + suffix := fmt.Sprintf(" (error: %v)", err) + if len(args) != 0 { + prefix = fmt.Sprintf(prefix, args...) + } + t.Fatal(prefix + suffix) + } +} diff --git a/testingx/testingx_test.go b/testingx/testingx_test.go new file mode 100644 index 0000000..314042d --- /dev/null +++ b/testingx/testingx_test.go @@ -0,0 +1,30 @@ +package testingx + +import ( + "errors" + "testing" +) + +type fakeReporter struct { + called int +} + +func (f *fakeReporter) Helper() {} +func (f *fakeReporter) Fatal(args ...interface{}) { + f.called++ +} + +func TestMust(t *testing.T) { + t.Run("success", func(t *testing.T) { + f := &fakeReporter{} + Must(f, nil, "print nothing") + if f.called != 0 { + t.Fatal("t.Fatal called with nil error!") + } + err := errors.New("fake error") + Must(f, err, "print nothing: %s", "custom args") + if f.called != 1 { + t.Fatal("t.Fatal NOT called with non-nil error!") + } + }) +}