How to use Cmp method of hooks Package

Best Go-testdeep code snippet using hooks.Cmp

hooks_test.go

Source:hooks_test.go Github

copy

Full Screen

...14 "time"15 "github.com/maxatome/go-testdeep/internal/hooks"16 "github.com/maxatome/go-testdeep/internal/test"17)18func TestAddCmpHooks(t *testing.T) {19 for _, tst := range []struct {20 name string21 cmp any22 err string23 }{24 {25 name: "not a function",26 cmp: "zip",27 err: "expects a function, not a string (@1)",28 },29 {30 name: "no variadic",31 cmp: func(a []byte, b ...byte) bool { return true },32 err: "expects: func (T, T) bool|error not func([]uint8, ...uint8) bool (@1)",33 },34 {35 name: "in",36 cmp: func(a, b, c int) bool { return true },37 err: "expects: func (T, T) bool|error not func(int, int, int) bool (@1)",38 },39 {40 name: "out",41 cmp: func(a, b int) {},42 err: "expects: func (T, T) bool|error not func(int, int) (@1)",43 },44 {45 name: "type mismatch",46 cmp: func(a int, b bool) bool { return true },47 err: "expects: func (T, T) bool|error not func(int, bool) bool (@1)",48 },49 {50 name: "interface",51 cmp: func(a, b any) bool { return true },52 err: "expects: func (T, T) bool|error not func(interface {}, interface {}) bool (@1)",53 },54 {55 name: "bad return",56 cmp: func(a, b int) int { return 0 },57 err: "expects: func (T, T) bool|error not func(int, int) int (@1)",58 },59 } {60 i := hooks.NewInfo()61 err := i.AddCmpHooks([]any{62 func(a, b bool) bool { return true },63 tst.cmp,64 })65 if test.Error(t, err, tst.name) {66 if !strings.Contains(err.Error(), tst.err) {67 t.Errorf("<%s> does not contain <%s> for %s", err, tst.err, tst.name)68 }69 }70 }71}72func TestCmp(t *testing.T) {73 t.Run("bool", func(t *testing.T) {74 var i *hooks.Info75 handled, err := i.Cmp(reflect.ValueOf(12), reflect.ValueOf(12))76 test.NoError(t, err)77 test.IsFalse(t, handled)78 i = hooks.NewInfo()79 err = i.AddCmpHooks([]any{func(a, b int) bool { return a == b }})80 test.NoError(t, err)81 handled, err = i.Cmp(reflect.ValueOf(12), reflect.ValueOf(12))82 test.NoError(t, err)83 test.IsTrue(t, handled)84 handled, err = i.Cmp(reflect.ValueOf(12), reflect.ValueOf(34))85 if err != hooks.ErrBoolean {86 test.EqualErrorMessage(t, err, hooks.ErrBoolean)87 }88 test.IsTrue(t, handled)89 handled, err = i.Cmp(reflect.ValueOf(12), reflect.ValueOf("twelve"))90 test.NoError(t, err)91 test.IsFalse(t, handled)92 handled, err = i.Cmp(reflect.ValueOf("twelve"), reflect.ValueOf("twelve"))93 test.NoError(t, err)94 test.IsFalse(t, handled)95 handled, err = (*hooks.Info)(nil).Cmp(reflect.ValueOf(1), reflect.ValueOf(2))96 test.NoError(t, err)97 test.IsFalse(t, handled)98 })99 t.Run("error", func(t *testing.T) {100 i := hooks.NewInfo()101 diffErr := errors.New("a≠b")102 err := i.AddCmpHooks([]any{103 func(a, b int) error {104 if a == b {105 return nil106 }107 return diffErr108 },109 })110 test.NoError(t, err)111 handled, err := i.Cmp(reflect.ValueOf(12), reflect.ValueOf(12))112 test.NoError(t, err)113 test.IsTrue(t, handled)114 handled, err = i.Cmp(reflect.ValueOf(12), reflect.ValueOf(34))115 if err != diffErr {116 test.EqualErrorMessage(t, err, diffErr)117 }118 test.IsTrue(t, handled)119 })120}121func TestSmuggle(t *testing.T) {122 var i *hooks.Info123 got := reflect.ValueOf(123)124 handled, err := i.Smuggle(&got)125 test.NoError(t, err)126 test.IsFalse(t, handled)127 i = hooks.NewInfo()128 err = i.AddSmuggleHooks([]any{func(a int) bool { return a != 0 }})...

Full Screen

Full Screen

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 {126 name: "abs",127 cmp: func(got int) int {128 if got < 0 {129 return -got130 }131 return got132 },133 got: -1234,134 expected: 1234,135 },136 {137 name: "int2bool",138 cmp: func(got int) bool { return got != 0 },139 got: 1,140 expected: true,141 },142 {143 name: "Atoi",144 cmp: strconv.Atoi,145 got: "1234",146 expected: 1234,147 },148 } {149 tt.Run(tst.name, func(tt *testing.T) {150 ttt := test.NewTestingTB(tt.Name())151 t := td.NewT(ttt)152 td.CmpFalse(tt, t.Cmp(tst.got, tst.expected))153 t = t.WithSmuggleHooks(tst.cmp)154 td.CmpTrue(tt, t.Cmp(tst.got, tst.expected))155 })156 }157 tt.Run("Error", func(tt *testing.T) {158 ttt := test.NewTestingTB(tt.Name())159 t := td.NewT(ttt).WithSmuggleHooks(func(got int) (int, error) {160 return 0, errors.New("never equal")161 })162 td.CmpFalse(tt, t.Cmp(1, 1))163 if !strings.Contains(ttt.LastMessage(), "DATA: never equal\n") {164 tt.Errorf(`<%s> does not contain "DATA: never equal\n"`, ttt.LastMessage())165 }166 })167 for _, tst := range []struct {168 name string169 cmp any170 fatal string171 }{172 {173 name: "not a function",174 cmp: "Booh",175 fatal: "WithSmuggleHooks expects a function, not a string",176 },...

Full Screen

Full Screen

Cmp

Using AI Code Generation

copy

Full Screen

1import (2type Hooks struct {3 PreInsert func()4 PreUpdate func()5 PreDelete func()6 PostInsert func()7 PostUpdate func()8 PostDelete func()9}10func (h *Hooks) Cmp(other *Hooks) bool {11 return reflect.DeepEqual(h, other)12}13func main() {14 h1 := Hooks{15 PreInsert: func() { fmt.Println("pre insert") },16 PreUpdate: func() { fmt.Println("pre update") },17 PreDelete: func() { fmt.Println("pre delete") },18 PostInsert: func() { fmt.Println("post insert") },19 PostUpdate: func() { fmt.Println("post update") },20 PostDelete: func() { fmt.Println("post delete") },21 }22 h2 := Hooks{23 PreInsert: func() { fmt.Println("pre insert") },24 PreUpdate: func() { fmt.Println("pre update") },25 PreDelete: func() { fmt.Println("pre delete") },26 PostInsert: func() { fmt.Println("post insert") },27 PostUpdate: func() { fmt.Println("post update") },28 PostDelete: func() { fmt.Println("post delete") },29 }30 h3 := Hooks{31 PreInsert: func() { fmt.Println("pre insert") },32 PreUpdate: func() { fmt.Println("pre update") },33 PreDelete: func() { fmt.Println("pre delete") },34 PostInsert: func() { fmt.Println("post insert") },35 PostUpdate: func() { fmt.Println("post update") },36 PostDelete: func() { fmt.Println("post delete") },37 }38 h4 := Hooks{39 PreInsert: func() { fmt.Println("pre insert") },40 PreUpdate: func() { fmt.Println("pre update") },41 PreDelete: func() { fmt.Println("pre delete") },42 PostInsert: func() { fmt.Println("post insert") },43 PostUpdate: func() { fmt.Println("post update") },44 PostDelete: func() { fmt.Println("post delete") },45 }46 h5 := Hooks{47 PreInsert: func() { fmt.Println("pre insert") },48 PreUpdate: func() { fmt.Println("pre update") },

Full Screen

Full Screen

Cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 logger.Log("Starting...")4 mods, err := module.NewModules()5 if err != nil {6 logger.LogErr(err, "Error initializing modules")7 }8 logger.Log("Modules initialized")9 h := hook.Hook{10 }11 err = mods.Hooks.Create(h)12 if err != nil {13 logger.LogErr(err, "Error creating hook")14 }15 logger.Log("Hook created")16 hook, err := mods.Hooks.RetrieveBySlug("test_hook")17 if err != nil {18 logger.LogErr(err, "Error retrieving hook")19 }20 logger.Log("Hook retrieved")21 fmt.Println("Hook retrieved: ", hook)22 err = mods.Hooks.Update(hook)23 if err != nil {24 logger.LogErr(err, "Error updating hook")25 }26 logger.Log("Hook updated")27 hook, err = mods.Hooks.RetrieveBySlug("test_hook")28 if err != nil {29 logger.LogErr(err, "Error retrieving hook")30 }31 logger.Log("Hook retrieved")32 fmt.Println("Hook retrieved: ", hook)33 err = mods.Hooks.Delete(hook)34 if err != nil {35 logger.LogErr(err, "Error deleting hook")36 }37 logger.Log("Hook deleted")38}39func init() {40 _ = resource.LoadDotEnv()41}

Full Screen

Full Screen

Cmp

Using AI Code Generation

copy

Full Screen

1import (2type Hooks struct {3}4func (h Hooks) String() string {5 return fmt.Sprintf("Name: %s, Version: %f", h.Name, h.Version)6}7func main() {8 hooks := []Hooks{9 {"pre-receive", 0.1},10 {"update", 0.2},11 {"post-receive", 0.3},12 }13 sort.Slice(hooks, func(i, j int) bool {14 })15 fmt.Println("Sorted Hooks: ", hooks)16}

Full Screen

Full Screen

Cmp

Using AI Code Generation

copy

Full Screen

1import (2type Student struct {3}4func main() {5 s1 := Student{"Alice", 20}6 s2 := Student{"Bob", 20}7 result := reflect.DeepEqual(s1, s2)8 fmt.Println(result)9}

Full Screen

Full Screen

Cmp

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 h := hooks.Hooks{}4 h.Cmp()5 fmt.Println("Hello")6}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful