From f28e5037bf9a3a58792c103b1833ac332b3ad54d Mon Sep 17 00:00:00 2001 From: Tadeo Kondrak Date: Thu, 13 Jul 2023 20:47:16 -0600 Subject: [PATCH] allow usage together with other golden packages (#45) * allow usage together with other golden packages Other packages can also define an -update flag. In general we can't be compatible with every possible conflicting flag, but for this specific flag we assume that it's a boolean flag with the same meaning as ours. My motivation for this change is usage of autogold along with gotest.tools/v3/assert, which among other things, has its own golden tests functionality. --------- Co-authored-by: Stephen Gutekanst --- autogold.go | 15 ++++++++++++--- expect.go | 4 ++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/autogold.go b/autogold.go index 8d30782..5c1f364 100644 --- a/autogold.go +++ b/autogold.go @@ -16,7 +16,6 @@ import ( ) var ( - update = flag.Bool("update", false, "update .golden files, leaving unused)") clean = flag.Bool("clean", false, "remove unused .golden files (slightly slower)") failOnUpdate = flag.Bool("fail-on-update", false, "If a .golden file is updated, fail the test") @@ -26,9 +25,19 @@ var ( ) func init() { + // For compatibility with other packages that also define an -update parameter, only define the + // flag if it's not already defined. + if updateFlag := flag.Lookup("update"); updateFlag == nil { + flag.Bool("update", false, "update .golden files, leaving unused)") + } + color.NoColor = false } +func update() bool { + return flag.Lookup("update").Value.(flag.Getter).Get().(bool) +} + // ExpectFile checks if got is equal to the saved `testdata/.golden` test file. If it is // not, the test is failed. // @@ -131,7 +140,7 @@ func ExpectFile(t *testing.T, got interface{}, opts ...Option) { os.Remove(outFile) } if diff != "" { - if *update { + if update() { grabLock() if _, err := os.Stat(dir); os.IsNotExist(err) { if err := os.MkdirAll(dir, 0o700); err != nil { @@ -142,7 +151,7 @@ func ExpectFile(t *testing.T, got interface{}, opts ...Option) { t.Fatal(err) } } - if *failOnUpdate || !*update { + if *failOnUpdate || !update() { t.Log(fmt.Errorf("mismatch (-want +got):\n%s", colorDiff(diff))) t.FailNow() } diff --git a/expect.go b/expect.go index dd8945a..c4d3162 100644 --- a/expect.go +++ b/expect.go @@ -156,7 +156,7 @@ func Expect(want interface{}) Value { } // Update the test file if so desired. - if *update { + if update() { // Acquire a file-level lock to prevent concurrent mutations to the _test.go file // by parallel tests (whether in-process, or not.) start = time.Now() @@ -181,7 +181,7 @@ func Expect(want interface{}) Value { t.Fatal(fmt.Errorf("autogold: %v", err)) } } - if *failOnUpdate || !*update { + if *failOnUpdate || !update() { writeProfile() t.Log(fmt.Errorf("mismatch (-want +got):\n%s", colorDiff(diff))) t.FailNow()