Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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].
//
Expand Down
20 changes: 20 additions & 0 deletions test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
18 changes: 18 additions & 0 deletions testdata/snapshots/TestTest/DiffReader/fail.snap
Original file line number Diff line number Diff line change
@@ -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

Loading