diff --git a/test.go b/test.go index 808f0d1..938972e 100644 --- a/test.go +++ b/test.go @@ -391,6 +391,30 @@ func DiffBytes(tb testing.TB, got, want []byte) { } } +// DiffReader reads data from both got and want [io.Reader] and provides +// a rich unified diff of the two for easy comparison. +// +// If either got or want do not end in a newline, one is added to avoid +// a "No newline at end of file" warning in the diff which is visually distracting. +func DiffReader(tb testing.TB, got, want io.Reader) { + tb.Helper() + + gotData, err := io.ReadAll(got) + if err != nil { + tb.Fatalf("DiffReader: could not read from got: %v\n", err) + } + + wantData, err := io.ReadAll(want) + if err != nil { + tb.Fatalf("DiffReader: could not read from want: %v\n", err) + } + + gotData = fixNL(gotData) + wantData = fixNL(wantData) + + DiffBytes(tb, gotData, wantData) +} + // CaptureOutput captures and returns data printed to [os.Stdout] and [os.Stderr] by the provided function fn, allowing // you to test functions that write to those streams and do not have an option to pass in an [io.Writer]. // diff --git a/test_test.go b/test_test.go index 113457c..bd40b83 100644 --- a/test_test.go +++ b/test_test.go @@ -451,6 +451,26 @@ func TestTest(t *testing.T) { }, wantFail: true, }, + { + name: "DiffReader/pass", + fn: func(tb testing.TB) { + got := []byte("Some\nstuff here in this file\nlines as well wow\nsome more stuff\n") + want := []byte("Some\nstuff here in this file\nlines as well wow\nsome more stuff\n") + + test.DiffReader(tb, bytes.NewReader(got), bytes.NewReader(want)) + }, + wantFail: false, + }, + { + name: "DiffReader/fail", + fn: func(tb testing.TB) { + got := []byte("Some\nstuff here in this file\nlines as well wow\nsome more stuff\n") + want := []byte("Some\ndifferent stuff here in this file\nthis line is different\nsome more stuff\n") + + test.DiffReader(tb, bytes.NewReader(got), bytes.NewReader(want)) + }, + wantFail: true, + }, } for _, tt := range tests { diff --git a/testdata/snapshots/TestTest/DiffReader/fail.snap b/testdata/snapshots/TestTest/DiffReader/fail.snap new file mode 100644 index 0000000..aac1d13 --- /dev/null +++ b/testdata/snapshots/TestTest/DiffReader/fail.snap @@ -0,0 +1,18 @@ +source: test_test.go +expression: buf.String() +--- +|2+ + + Diff + ---- + diff want got + --- want + +++ got + @@ -1,4 +1,4 @@ + Some + - different stuff here in this file + - this line is different + + stuff here in this file + + lines as well wow + some more stuff +