From bae07880a7b7e65701a45ecbb32914e6552626a5 Mon Sep 17 00:00:00 2001 From: Kevin Smithson Date: Wed, 14 Sep 2022 01:13:32 -0700 Subject: [PATCH] Add option to specify custom snapshot differ (#64) * Add option to specify custom snapshot differ * Update updateShapshot to use the differ * Update config.go Co-authored-by: Bradley Kemp Co-authored-by: Bradley Kemp --- config.go | 12 ++++++++++++ cupaloy.go | 2 +- util.go | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/config.go b/config.go index 811c49c..91e8079 100644 --- a/config.go +++ b/config.go @@ -76,6 +76,15 @@ func SnapshotFileExtension(snapshotFileExtension string) Configurator { } } +// DiffSnapshots allows you to change the diffing function used to display the +// difference between the previous snapshot and the current. +// Default: Internal differ using difflib +func DiffSnapshots(differ func(previous, current string) string) Configurator { + return func(c *Config) { + c.diffSnapshots = differ + } +} + // UseStringerMethods invoke String() or Error() methods when available rather than dumping the object. // This should probably be disabled by default but is not for backwards compatibility reasons. // Default: true @@ -93,6 +102,7 @@ type Config struct { createNewAutomatically bool fatalOnMismatch bool snapshotFileExtension string + diffSnapshots func(previous, current string) string useStringerMethods bool } @@ -106,6 +116,7 @@ func NewDefaultConfig() *Config { CreateNewAutomatically(true), FatalOnMismatch(false), SnapshotFileExtension(""), + DiffSnapshots(diffSnapshots), UseStringerMethods(true), ) } @@ -121,6 +132,7 @@ func (c *Config) clone() *Config { createNewAutomatically: c.createNewAutomatically, fatalOnMismatch: c.fatalOnMismatch, snapshotFileExtension: c.snapshotFileExtension, + diffSnapshots: c.diffSnapshots, useStringerMethods: c.useStringerMethods, } } diff --git a/cupaloy.go b/cupaloy.go index 50964b7..cb704a0 100644 --- a/cupaloy.go +++ b/cupaloy.go @@ -133,6 +133,6 @@ func (c *Config) snapshot(snapshotName string, i ...interface{}) error { } return internal.ErrSnapshotMismatch{ - Diff: diffSnapshots(prevSnapshot, snapshot), + Diff: c.diffSnapshots(prevSnapshot, snapshot), } } diff --git a/util.go b/util.go index 57c8fd1..303a026 100644 --- a/util.go +++ b/util.go @@ -114,7 +114,7 @@ func (c *Config) updateSnapshot(snapshotName string, prevSnapshot string, snapsh return nil } - snapshotDiff := diffSnapshots(prevSnapshot, snapshot) + snapshotDiff := c.diffSnapshots(prevSnapshot, snapshot) if isNewSnapshot { return internal.ErrSnapshotCreated{