How to use WithCmpHooks method of td Package

Best Go-testdeep code snippet using td.WithCmpHooks

t_hooks.go

Source:t_hooks.go Github

copy

Full Screen

...6package td7import (8 "github.com/maxatome/go-testdeep/internal/color"9)10// WithCmpHooks returns a new [*T] instance with new Cmp hooks recorded11// using functions passed in fns.12//13// Each function in fns has to be a function with the following14// possible signatures:15//16// func (got A, expected A) bool17// func (got A, expected A) error18//19// First arg is always got, and second is always expected.20//21// A cannot be an interface. This restriction can be removed in the22// future, if really needed.23//24// This function is called as soon as possible each time the type A is25// encountered for got while expected type is assignable to A.26//27// When it returns a bool, false means A is not equal to B.28//29// When it returns a non-nil error (meaning got ≠ expected), its30// content is used to tell the reason of the failure.31//32// Cmp hooks are checked before [UseEqual] feature.33//34// Cmp hooks are run just after [Smuggle] hooks.35//36// func TestCmpHook(tt *testing.T) {37// t := td.NewT(tt)38//39// // Test reflect.Value contents instead of default field/field40// t = t.WithCmpHooks(func (got, expected reflect.Value) bool {41// return td.EqDeeply(got.Interface(), expected.Interface())42// })43// a, b := 1, 144// t.Cmp(reflect.ValueOf(&a), reflect.ValueOf(&b)) // succeeds45//46// // Test reflect.Type correctly instead of default field/field47// t = t.WithCmpHooks(func (got, expected reflect.Type) bool {48// return got == expected49// })50//51// // Test time.Time via its Equal() method instead of default52// // field/field (note it bypasses the UseEqual flag)53// t = t.WithCmpHooks((time.Time).Equal)54// date, _ := time.Parse(time.RFC3339, "2020-09-08T22:13:54+02:00")55// t.Cmp(date, date.UTC()) // succeeds56//57// // Several hooks can be declared at once58// t = t.WithCmpHooks(59// func (got, expected reflect.Value) bool {60// return td.EqDeeply(got.Interface(), expected.Interface())61// },62// func (got, expected reflect.Type) bool {63// return got == expected64// },65// (time.Time).Equal,66// )67// }68//69// There is no way to add or remove hooks of an existing [*T]70// instance, only to create a new [*T] instance with this method or71// [T.WithSmuggleHooks] to add some.72//73// WithCmpHooks calls t.Fatal if an item of fns is not a function or74// if its signature does not match the expected ones.75//76// See also [T.WithSmuggleHooks].77//78// [UseEqual]: https://pkg.go.dev/github.com/maxatome/go-testdeep/td#ContextConfig.UseEqual79func (t *T) WithCmpHooks(fns ...any) *T {80 t = t.copyWithHooks()81 err := t.Config.hooks.AddCmpHooks(fns)82 if err != nil {83 t.Helper()84 t.Fatal(color.Bad("WithCmpHooks " + err.Error()))85 }86 return t87}88// WithSmuggleHooks returns a new [*T] instance with new Smuggle hooks89// recorded using functions passed in fns.90//91// Each function in fns has to be a function with the following92// possible signatures:93//94// func (got A) B95// func (got A) (B, error)96//97// A cannot be an interface. This restriction can be removed in the98// future, if really needed.99//100// B cannot be an interface. If you have a use case, we can talk about it.101//102// This function is called as soon as possible each time the type A is103// encountered for got.104//105// The B value returned replaces the got value for subsequent tests.106// Smuggle hooks are NOT run again for this returned value to avoid107// easy infinite loop recursion.108//109// When it returns non-nil error (meaning something wrong happened110// during the conversion of A to B), it raises a global error and its111// content is used to tell the reason of the failure.112//113// Smuggle hooks are run just before Cmp hooks.114//115// func TestSmuggleHook(tt *testing.T) {116// t := td.NewT(tt)117//118// // Each encountered int is changed to a bool119// t = t.WithSmuggleHooks(func (got int) bool {120// return got != 0121// })122// t.Cmp(map[string]int{"ok": 1, "no": 0},123// map[string]bool{"ok", true, "no", false}) // succeeds124//125// // Each encountered string is converted to int126// t = t.WithSmuggleHooks(strconv.Atoi)127// t.Cmp("123", 123) // succeeds128//129// // Several hooks can be declared at once130// t = t.WithSmuggleHooks(131// func (got int) bool { return got != 0 },132// strconv.Atoi,133// )134// }135//136// There is no way to add or remove hooks of an existing [*T]137// instance, only create a new [*T] instance with this method or138// [T.WithCmpHooks] to add some.139//140// WithSmuggleHooks calls t.Fatal if an item of fns is not a141// function or if its signature does not match the expected ones.142//143// See also [T.WithCmpHooks].144func (t *T) WithSmuggleHooks(fns ...any) *T {145 t = t.copyWithHooks()146 err := t.Config.hooks.AddSmuggleHooks(fns)147 if err != nil {148 t.Helper()149 t.Fatal(color.Bad("WithSmuggleHooks " + err.Error()))150 }151 return t152}153func (t *T) copyWithHooks() *T {154 nt := NewT(t)155 nt.Config.hooks = t.Config.hooks.Copy()156 return nt157}...

Full Screen

Full Screen

t_hooks_test.go

Source:t_hooks_test.go Github

copy

Full Screen

...14 "time"15 "github.com/maxatome/go-testdeep/internal/test"16 "github.com/maxatome/go-testdeep/td"17)18func TestWithCmpHooks(tt *testing.T) {19 na, nb := 1234, 123420 date, _ := time.Parse(time.RFC3339, "2020-09-08T22:13:54+02:00")21 for _, tst := range []struct {22 name string23 cmp any24 got, expected any25 }{26 {27 name: "reflect.Value",28 cmp: func(got, expected reflect.Value) bool {29 return td.EqDeeply(got.Interface(), expected.Interface())30 },31 got: reflect.ValueOf(&na),32 expected: reflect.ValueOf(&nb),33 },34 {35 name: "time.Time",36 cmp: (time.Time).Equal,37 got: date,38 expected: date.UTC(),39 },40 {41 name: "numify",42 cmp: func(got, expected string) error {43 ngot, err := strconv.Atoi(got)44 if err != nil {45 return fmt.Errorf("strconv.Atoi(got) failed: %s", err)46 }47 nexpected, err := strconv.Atoi(expected)48 if err != nil {49 return fmt.Errorf("strconv.Atoi(expected) failed: %s", err)50 }51 if ngot != nexpected {52 return errors.New("values differ")53 }54 return nil55 },56 got: "0000001234",57 expected: "1234",58 },59 {60 name: "false test :)",61 cmp: func(got, expected int) bool {62 return got == -expected63 },64 got: 1,65 expected: -1,66 },67 } {68 tt.Run(tst.name, func(tt *testing.T) {69 ttt := test.NewTestingTB(tt.Name())70 t := td.NewT(ttt)71 td.CmpFalse(tt, func() bool {72 // A panic can occur when -tags safe:73 // dark.GetInterface() does not handle private unsafe.Pointer kind74 defer func() { recover() }() //nolint: errcheck75 return t.Cmp(tst.got, tst.expected)76 }())77 t = t.WithCmpHooks(tst.cmp)78 td.CmpTrue(tt, t.Cmp(tst.got, tst.expected))79 })80 }81 tt.Run("Error", func(tt *testing.T) {82 ttt := test.NewTestingTB(tt.Name())83 t := td.NewT(ttt).84 WithCmpHooks(func(got, expected int) error {85 return errors.New("never equal")86 })87 td.CmpFalse(tt, t.Cmp(1, 1))88 if !strings.Contains(ttt.LastMessage(), "DATA: never equal\n") {89 tt.Errorf(`<%s> does not contain "DATA: never equal\n"`, ttt.LastMessage())90 }91 })92 for _, tst := range []struct {93 name string94 cmp any95 fatal string96 }{97 {98 name: "not a function",99 cmp: "Booh",100 fatal: "WithCmpHooks expects a function, not a string",101 },102 {103 name: "wrong signature",104 cmp: func(a []int, b ...int) bool { return false },105 fatal: "WithCmpHooks expects: func (T, T) bool|error not ",106 },107 } {108 tt.Run("panic: "+tst.name, func(tt *testing.T) {109 ttt := test.NewTestingTB(tt.Name())110 t := td.NewT(ttt)111 fatalMesg := ttt.CatchFatal(func() { t.WithCmpHooks(tst.cmp) })112 test.IsTrue(tt, ttt.IsFatal)113 if !strings.Contains(fatalMesg, tst.fatal) {114 tt.Errorf(`<%s> does not contain %q`, fatalMesg, tst.fatal)115 }116 })117 }118}119func TestWithSmuggleHooks(tt *testing.T) {120 for _, tst := range []struct {121 name string122 cmp any123 got, expected any124 }{125 {...

Full Screen

Full Screen

parser_test.go

Source:parser_test.go Github

copy

Full Screen

...34 wantFile, err := parser.ParseFile(wantFset, "test.bake", goSrcReader, 0)35 t.CmpNoError(err)36 {37 // ignore some fields, so that we could use t.Cmp38 t = t.WithCmpHooks(func(token.Pos, token.Pos) error { return nil }) // ignoring just to simplify the comparison39 t = t.WithCmpHooks(func(*ast.Object, *ast.Object) error { return nil }) // not used40 wantFile.Scope = nil // not used41 wantFile.Unresolved = nil // not used42 wantFile.Imports = nil // imports are added in wantFile.Decls43 }44 if !t.Cmp(gotFile, wantFile) {45 ast.Print(prsr.FileSet, gotFile)46 t.FailNow()47 }48}...

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 td.Cmp(t, 1, td.WithCmpHooks(4 func(got, expected interface{}) bool {5 },6 func(got, expected interface{}) string {7 },8}9import (10func main() {11 td.Cmp(t, 1, td.WithCmpHook(12 func(got, expected interface{}) bool {13 },14}15import (16func main() {17 td.Cmp(t, 1, td.WithCmpHookDeeply(18 func(got, expected interface{}) bool {19 },20}21import (22func main() {23 td.Cmp(t, 1, td.WithCmpHookDeeply(24 func(got, expected interface{}) bool {25 },26 func(got, expected interface{}) string {27 },28}29import (

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func main() {5 u := User{Name: "Bob"}6 fmt.Println(td.Cmp(u, td.WithCmpHooks(td.CmpOptions{}, func(ctx td.CmpContext) bool {7 if ctx.Value.Kind() == td.KindStruct {8 ctx.Value = ctx.Value.MapIndex(td.String("Name"))9 }10 })))11}

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(testdeep.Cmp(a, b, c, d, e, f, g, h))4 fmt.Println(testdeep.Cmp(a, b, c, d, e, f, g, h, testdeep.WithCmpHooks(testdeep.CmpHooks{5 testdeep.IntType: func(a, b int) bool {6 },7 })))8}

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2type TestSuite struct {3}4func (s *TestSuite) TestWithCmpHooks() {5 var actual = []string{"a", "b", "c"}6 var expected = []string{"c", "b", "a"}7 var cmp = toolbox.NewCmp()8 cmp.WithCmpHooks(func(actual interface{}, expected interface{}) bool {9 if actualSlice, ok := actual.([]string); ok {10 if expectedSlice, ok := expected.([]string); ok {11 sort.Strings(actualSlice)12 sort.Strings(expectedSlice)13 return toolbox.Cmp(actualSlice, expectedSlice, cmp)14 }15 }16 })17 assert.True(s.T(), toolbox.Cmp(actual, expected, cmp))18}19func TestTestSuite(t *testing.T) {20 suite.Run(t, new(TestSuite))21}22import (23type TestSuite struct {24}25func (s *TestSuite) TestWithCmpHooks() {26 var actual = map[string]string{"a": "a", "b": "b", "c": "c"}27 var expected = map[string]string{"c": "c", "b": "b", "a": "a"}28 var cmp = toolbox.NewCmp()29 cmp.WithCmpHooks(func(actual interface{}, expected interface{}) bool {30 if actualMap, ok := actual.(map[string]string); ok {31 if expectedMap, ok := expected.(map[string]string); ok {32 var actualKeys = make([]string, 0)33 var expectedKeys = make([]string, 0)34 for k := range actualMap {

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2type myStruct struct {3}4func main() {5 testdeep.CmpDeeply(myStruct{1, "a"}, myStruct{1, "a"})6 testdeep.CmpDeeply(myStruct{1, "a"}, myStruct{1, "b"})7}8--- FAIL: TestCmp (0.00s)9 got: struct { a int; b string }{a:1, b:"b"}10 want: struct { a int; b string }{a:1, b:"a"}11--- PASS: TestCmp (0.00s)12import (13type myStruct struct {14}15func main() {16 testdeep.CmpDeeply(myStruct{1, "a"}, myStruct{1, "a"},17 testdeep.WithCmpHooks(func(got, want interface{}) error {18 fmt.Printf("got: %v, want: %v19 }))20 testdeep.CmpDeeply(myStruct{1, "a"}, myStruct{1, "b"},21 testdeep.WithCmpHooks(func(got, want interface{}) error {22 fmt.Printf("got: %v, want: %v23 }))24}25--- FAIL: TestCmp (0.00s)26 got: struct { a int; b string }{a:1, b:"b"}

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 type T struct {4 }5 td.CmpHooks[T] = func(t1, t2 T) bool {6 }7 td.CmpHooks[*T] = func(t1, t2 *T) bool {8 }9 td.CmpHooks[[]T] = func(t1, t2 []T) bool {10 }11 td.CmpHooks[[]*T] = func(t1, t2 []*T) bool {12 }13 fmt.Println(td.Cmp(T{"Bob", 42}, T{"Bob", 99}))14 fmt.Println(td.Cmp(&T{"Bob", 42}, &T{"Bob", 99}))15 fmt.Println(td.Cmp([]T{{"Bob", 42}}, []T{{"Bob", 99}}))16 fmt.Println(td.Cmp([]*T{{"Bob", 42}}, []*T{{"Bob", 99}}))17}18import (19func main() {20 type T struct {21 }22 td.CmpHooks[T] = func(t1, t2 T) bool {23 }24 td.CmpHooks[*T] = func(t1, t2 *T) bool {25 }26 td.CmpHooks[[]T] = func(t1, t2 []T) bool {27 }

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 td.CmpHooks(4 td.Smuggle(func(val int) string {5 return fmt.Sprintf("%d", val)6 }, td.String()),7 td.Smuggle(func(val string) int {8 return len(val)9 }, td.Int()),10 ).Cmp(123, "3")11}12import (13func main() {14 td.CmpHooks(15 td.Smuggle(func(val int) string {16 return fmt.Sprintf("%d", val)17 }, td.String()),18 td.Smuggle(func(val string) int {19 return len(val)20 }, td.Int()),21 ).Cmp(123, "3")22}23import (24func main() {25 td.CmpHooks(26 td.Smuggle(func(val int) string {27 return fmt.Sprintf("%d", val)28 }, td.String()),

Full Screen

Full Screen

WithCmpHooks

Using AI Code Generation

copy

Full Screen

1func main() {2 test := td.NewTest(t)3 td := test.TD()4 td = td.WithCmpHooks(5 td.CmpHook(reflect.TypeOf((*MyInt)(nil)), func(a, b reflect.Value) bool {6 return a.Interface().(MyInt).Value == b.Interface().(MyInt).Value7 }),8}9[MIT](LICENSE)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Go-testdeep automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful