Last active
February 7, 2023 22:44
-
-
Save StevenACoffman/74347e58e5e0dc4bdf0a79240557c406 to your computer and use it in GitHub Desktop.
Golang Testify go-cmp Partial Equal
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 | |
import ( | |
"fmt" | |
"testing" | |
"time" | |
"github.com/google/go-cmp/cmp" | |
"github.com/google/go-cmp/cmp/cmpopts" | |
"github.com/stretchr/testify/assert" | |
"github.com/stretchr/testify/require" | |
) | |
type B struct { | |
Foo time.Time | |
Bar time.Time | |
} | |
type A struct { | |
B | |
C int | |
} | |
func TestStructPartialEquality(t *testing.T) { | |
a1 := A{B: B{Foo: time.Unix(1, 0)}, C: 3} | |
a2 := a1 | |
a2.Foo = time.Unix(2, 0) | |
a2.Bar = time.Now() // comment to PASS, uncomment to FAIL | |
diffOpts := cmpopts.IgnoreFields(a2, "B.Foo") | |
PartialEqual(t, a1, a2, diffOpts) | |
//require.True(t, cmp.Equal(a1, a2, diffOpts), cmp.Diff(a1, a2, diffOpts)) | |
// diff := cmp.Diff(a1, a2, cmpopts.IgnoreFields(A{}, "B.Foo")) | |
// | |
// if diff != "" { | |
// t.Errorf("THE DIFF %+v", diff) | |
// } | |
} | |
// PartialEqual asserts that two objects are equal, depending on what equal means | |
// | |
// For instance, you may pass options to ignore certain fields | |
func PartialEqual(t require.TestingT, expected, actual any, diffOpts cmp.Option, msgAndArgs ...any) { | |
if h, ok := t.(tHelper); ok { | |
h.Helper() | |
} | |
if cmp.Equal(expected, actual, diffOpts) { | |
return | |
} | |
diff := cmp.Diff(expected, actual, diffOpts) | |
assert.Fail(t, fmt.Sprintf("Not equal: \n"+ | |
"expected: %s\n"+ | |
"actual : %s%s", expected, actual, diff), msgAndArgs...) | |
return | |
} | |
type tHelper interface { | |
Helper() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment