Last active
September 4, 2020 08:16
-
-
Save danielwhite/f11894aaf18705606317569539e93eb7 to your computer and use it in GitHub Desktop.
Simple golden file test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main_test | |
import ( | |
"testing" | |
) | |
/* | |
This is an example implementation of a golden file test that is easy to update. | |
*/ | |
// Run test with "go test -update" to regenerate golden files. | |
var updateFlag = flag.Bool("update", false, "If set, golden files are updated.") | |
func TestGolden(t *testing.T) { | |
const goldenFile = "testdata/golden.txt" | |
// Capture test output in a buffer. | |
buf := new(bytes.Buffer) | |
buf.WriteString("output from test...") | |
// Compare the output to a golden file. | |
checkDiff(t, goldenFile, buf.Bytes(), *updateFlag) | |
} | |
// checkDiff checks the changes between the contents of file "from" | |
// and the contents of "to". If this fails, then the test is marked as | |
// having failed. | |
// | |
// If update is true, then the contents of the golden file is updated. | |
func checkDiff(tb testing.TB, from string, to []byte, update bool) { | |
tb.Helper() | |
if err := diff(from, to); err != nil { | |
if update { | |
if err := ioutil.WriteFile(from, to, 0644); err != nil { | |
tb.Error(err) | |
} | |
} | |
tb.Fatal(err) | |
} | |
} | |
// diff checks the changes between the contents of file "from" and the | |
// contents of "to". If this fails, then the diff is included in the | |
// error. | |
func diff(from string, to []byte) (err error) { | |
cmd := exec.Command("diff", "-u", "--from-file="+from, "-") | |
cmd.Stdin = bytes.NewReader(to) | |
var out bytes.Buffer | |
cmd.Stdout = &out | |
cmd.Stderr = &out | |
if err = cmd.Run(); err != nil { | |
err = fmt.Errorf("%v: %s", err, &out) | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment