diff --git a/README.md b/README.md index 94c120d..f4bb559 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,29 @@ func TestOutput(t *testing.T) { Under the hood `CaptureOutput` temporarily captures both streams, copies the data to a buffer and returns the output back to you, before cleaning everything back up again. +### Golden Files + +`test` has great support for golden files: + +```go +func TestFile(t *testing.T) { + got := "some contents\n" + want := filepath.Join(test.Data(t), "golden.txt") + + test.File(t, got, want) +} +``` + +This wil read the file, normalise line endings and then generate an output almost like a git diff: + +```patch +--- want ++++ got +@@ -1 +1 @@ +-some file contents ++some contents +``` + ### Credits This package was created with [copier] and the [FollowTheProcess/go_copier] project template. diff --git a/go.mod b/go.mod index 9b07055..90512b7 100644 --- a/go.mod +++ b/go.mod @@ -3,3 +3,5 @@ module github.com/FollowTheProcess/test go 1.22 require github.com/google/go-cmp v0.6.0 + +require github.com/aymanbagabas/go-udiff v0.2.0 diff --git a/go.sum b/go.sum index 5a8d551..88ba967 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,4 @@ +github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= +github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= diff --git a/test.go b/test.go index cafcca9..3521657 100644 --- a/test.go +++ b/test.go @@ -12,6 +12,7 @@ import ( "sync" "testing" + "github.com/aymanbagabas/go-udiff" "github.com/google/go-cmp/cmp" ) @@ -193,7 +194,8 @@ func Data(t testing.TB) string { // It takes a string and the path of a file to compare, use [Data] to obtain // the path to the current packages testdata directory. // -// If the contents differ, the test will fail with output equivalent to [Diff]. +// If the contents differ, the test will fail with output similar to executing git diff +// on the contents. // // Files with differing line endings (e.g windows CR LF \r\n vs unix LF \n) will be normalised to // \n prior to comparison so this function will behave identically across multiple platforms. @@ -212,7 +214,9 @@ func File(t testing.TB, got, file string) { contents = bytes.ReplaceAll(contents, []byte("\r\n"), []byte("\n")) - Diff(t, got, string(contents)) + if diff := udiff.Unified("want", "got", string(contents), got); diff != "" { + t.Fatalf("\nMismatch\n--------\n%s\n", diff) + } } // CaptureOutput captures and returns data printed to stdout and stderr by the provided function fn, allowing