Best Go-testdeep code snippet using td_test.TestCode
td_code_test.go
Source:td_code_test.go
...14 "github.com/maxatome/go-testdeep/internal/ctxerr"15 "github.com/maxatome/go-testdeep/internal/test"16 "github.com/maxatome/go-testdeep/td"17)18func TestCode(t *testing.T) {19 checkOK(t, 12, td.Code(func(n int) bool { return n >= 10 && n < 20 }))20 checkOK(t, 12, td.Code(func(val any) bool {21 num, ok := val.(int)22 return ok && num == 1223 }))24 checkOK(t, errors.New("foobar"), td.Code(func(val error) bool {25 return val.Error() == "foobar"26 }))27 checkOK(t, json.RawMessage(`[42]`),28 td.Code(func(b json.RawMessage) error {29 var l []int30 err := json.Unmarshal(b, &l)31 if err != nil {32 return err33 }34 if len(l) != 1 || l[0] != 42 {35 return errors.New("42 not found")36 }37 return nil38 }))39 // Lax40 checkOK(t, 123, td.Lax(td.Code(func(n float64) bool { return n == 123 })))41 checkError(t, 123, td.Code(func(n float64) bool { return true }),42 expectedError{43 Message: mustBe("incompatible parameter type"),44 Path: mustBe("DATA"),45 Got: mustBe("int"),46 Expected: mustBe("float64"),47 })48 type xInt int49 checkError(t, xInt(12),50 td.Code(func(n int) bool { return n >= 10 && n < 20 }),51 expectedError{52 Message: mustBe("incompatible parameter type"),53 Path: mustBe("DATA"),54 Got: mustBe("td_test.xInt"),55 Expected: mustBe("int"),56 })57 checkError(t, 12,58 td.Code(func(n int) (bool, string) { return false, "custom error" }),59 expectedError{60 Message: mustBe("ran code with %% as argument"),61 Path: mustBe("DATA"),62 Summary: mustBe(" value: 12\nit failed coz: custom error"),63 })64 checkError(t, 12,65 td.Code(func(n int) bool { return false }),66 expectedError{67 Message: mustBe("ran code with %% as argument"),68 Path: mustBe("DATA"),69 Summary: mustBe(" value: 12\nit failed but didn't say why"),70 })71 type MyBool bool72 type MyString string73 checkError(t, 12,74 td.Code(func(n int) (MyBool, MyString) { return false, "very custom error" }),75 expectedError{76 Message: mustBe("ran code with %% as argument"),77 Path: mustBe("DATA"),78 Summary: mustBe(" value: 12\nit failed coz: very custom error"),79 })80 checkError(t, 12,81 td.Code(func(i int) error {82 return errors.New("very custom error")83 }),84 expectedError{85 Message: mustBe("ran code with %% as argument"),86 Path: mustBe("DATA"),87 Summary: mustBe(" value: 12\nit failed coz: very custom error"),88 })89 // Internal use90 checkError(t, 12,91 td.Code(func(i int) error {92 return &ctxerr.Error{93 Message: "my message",94 Summary: ctxerr.NewSummary("my summary"),95 }96 }),97 expectedError{98 Message: mustBe("my message"),99 Path: mustBe("DATA"),100 Summary: mustBe("my summary"),101 })102 //103 // Bad usage104 checkError(t, "never tested",105 td.Code(nil),106 expectedError{107 Message: mustBe("bad usage of Code operator"),108 Path: mustBe("DATA"),109 Summary: mustBe("usage: Code(FUNC), but received nil as 1st parameter"),110 })111 checkError(t, "never tested",112 td.Code((func(string) bool)(nil)),113 expectedError{114 Message: mustBe("bad usage of Code operator"),115 Path: mustBe("DATA"),116 Summary: mustBe("Code(FUNC): FUNC cannot be a nil function"),117 })118 checkError(t, "never tested",119 td.Code("test"),120 expectedError{121 Message: mustBe("bad usage of Code operator"),122 Path: mustBe("DATA"),123 Summary: mustBe("usage: Code(FUNC), but received string as 1st parameter"),124 })125 checkError(t, "never tested",126 td.Code(func(x ...int) bool { return true }),127 expectedError{128 Message: mustBe("bad usage of Code operator"),129 Path: mustBe("DATA"),130 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),131 })132 checkError(t, "never tested",133 td.Code(func() bool { return true }),134 expectedError{135 Message: mustBe("bad usage of Code operator"),136 Path: mustBe("DATA"),137 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),138 })139 checkError(t, "never tested",140 td.Code(func(a, b, c, d string) bool { return true }),141 expectedError{142 Message: mustBe("bad usage of Code operator"),143 Path: mustBe("DATA"),144 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),145 })146 checkError(t, "never tested",147 td.Code(func(a int, b string) bool { return true }),148 expectedError{149 Message: mustBe("bad usage of Code operator"),150 Path: mustBe("DATA"),151 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),152 })153 checkError(t, "never tested",154 td.Code(func(t *td.T, a int, b string) bool { return true }),155 expectedError{156 Message: mustBe("bad usage of Code operator"),157 Path: mustBe("DATA"),158 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),159 })160 checkError(t, "never tested", // because it is certainly an error161 td.Code(func(assert, require *td.T) bool { return true }),162 expectedError{163 Message: mustBe("bad usage of Code operator"),164 Path: mustBe("DATA"),165 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),166 })167 checkError(t, "never tested",168 td.Code(func(n int) (bool, int) { return true, 0 }),169 expectedError{170 Message: mustBe("bad usage of Code operator"),171 Path: mustBe("DATA"),172 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),173 })174 checkError(t, "never tested",175 td.Code(func(n int) (error, string) { return nil, "" }), //nolint: staticcheck176 expectedError{177 Message: mustBe("bad usage of Code operator"),178 Path: mustBe("DATA"),179 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),180 })181 checkError(t, "never tested",182 td.Code(func(n int) (int, string) { return 0, "" }),183 expectedError{184 Message: mustBe("bad usage of Code operator"),185 Path: mustBe("DATA"),186 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),187 })188 checkError(t, "never tested",189 td.Code(func(n int) (string, bool) { return "", true }),190 expectedError{191 Message: mustBe("bad usage of Code operator"),192 Path: mustBe("DATA"),193 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),194 })195 checkError(t, "never tested",196 td.Code(func(n int) (bool, string, int) { return true, "", 0 }),197 expectedError{198 Message: mustBe("bad usage of Code operator"),199 Path: mustBe("DATA"),200 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),201 })202 checkError(t, "never tested",203 td.Code(func(n int) {}),204 expectedError{205 Message: mustBe("bad usage of Code operator"),206 Path: mustBe("DATA"),207 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),208 })209 checkError(t, "never tested",210 td.Code(func(n int) int { return 0 }),211 expectedError{212 Message: mustBe("bad usage of Code operator"),213 Path: mustBe("DATA"),214 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),215 })216 checkError(t, "never tested",217 td.Code(func(t *td.T, a int) bool { return true }),218 expectedError{219 Message: mustBe("bad usage of Code operator"),220 Path: mustBe("DATA"),221 Summary: mustBe("Code(FUNC): FUNC must return nothing"),222 })223 checkError(t, "never tested",224 td.Code(func(assert, require *td.T, a int) bool { return true }),225 expectedError{226 Message: mustBe("bad usage of Code operator"),227 Path: mustBe("DATA"),228 Summary: mustBe("Code(FUNC): FUNC must return nothing"),229 })230 //231 // String232 test.EqualStr(t,233 td.Code(func(n int) bool { return false }).String(),234 "Code(func(int) bool)")235 test.EqualStr(t,236 td.Code(func(n int) (bool, string) { return false, "" }).String(),237 "Code(func(int) (bool, string))")238 test.EqualStr(t,239 td.Code(func(n int) error { return nil }).String(),240 "Code(func(int) error)")241 test.EqualStr(t,242 td.Code(func(n int) (MyBool, MyString) { return false, "" }).String(),243 "Code(func(int) (td_test.MyBool, td_test.MyString))")244 // Erroneous op245 test.EqualStr(t, td.Code(nil).String(), "Code(<ERROR>)")246}247func TestCodeCustom(t *testing.T) {248 // Specific _checkOK func as td.Code(FUNC) with FUNC(t,arg) or249 // FUNC(assert,require,arg) works in non-boolean context but cannot250 // work in boolean context as there is no initial testing.TB instance251 _customCheckOK := func(t *testing.T, got, expected any, args ...any) bool {252 t.Helper()253 if !td.Cmp(t, got, expected, args...) {254 return false255 }256 // Should always fail in boolean context as no original testing.TB available257 err := td.EqDeeplyError(got, expected)258 if err == nil {259 t.Error(`Boolean context succeeded and it shouldn't`)260 return false261 }262 expErr := expectedError{263 Message: mustBe("cannot build *td.T instance"),264 Path: mustBe("DATA"),265 Summary: mustBe("original testing.TB instance is missing"),266 }267 if !strings.HasPrefix(expected.(fmt.Stringer).String(), "Code") {268 expErr = ifaceExpectedError(t, expErr)269 }270 if !matchError(t, err.(*ctxerr.Error), expErr, true, args...) {271 return false272 }273 if td.EqDeeply(got, expected) {274 t.Error(`Boolean context succeeded and it shouldn't`)275 return false276 }277 return true278 }279 customCheckOK(t, _customCheckOK, 123, td.Code(func(t *td.T, n int) {280 t.Cmp(t.Config.FailureIsFatal, false)281 t.Cmp(n, 123)282 }))283 customCheckOK(t, _customCheckOK, 123, td.Code(func(assert, require *td.T, n int) {284 assert.Cmp(assert.Config.FailureIsFatal, false)285 assert.Cmp(require.Config.FailureIsFatal, true)286 assert.Cmp(n, 123)287 require.Cmp(n, 123)288 }))289 got := map[string]int{"foo": 123}290 t.Run("Simple success", func(t *testing.T) {291 mockT := test.NewTestingTB("TestCodeCustom")292 td.Cmp(mockT, got, td.Map(map[string]int{}, td.MapEntries{293 "foo": td.Code(func(t *td.T, n int) {294 t.Cmp(n, 123)295 }),296 }))297 test.EqualInt(t, len(mockT.Messages), 0)298 })299 t.Run("Simple failure", func(t *testing.T) {300 mockT := test.NewTestingTB("TestCodeCustom")301 td.NewT(mockT).302 RootName("PIPO").303 Cmp(got, td.Map(map[string]int{}, td.MapEntries{304 "foo": td.Code(func(t *td.T, n int) {305 t.Cmp(n, 124) // inherit only RootName306 t.RootName(t.Config.OriginalPath()).Cmp(n, 125) // recover current path307 t.RootName("").Cmp(n, 126) // undo RootName inheritance308 }),309 }))310 test.IsTrue(t, mockT.HasFailed)311 test.IsFalse(t, mockT.IsFatal)312 missing := mockT.ContainsMessages(313 `PIPO: values differ`,314 ` got: 123`,315 `expected: 124`,316 `PIPO["foo"]: values differ`,317 ` got: 123`,318 `expected: 125`,319 `DATA: values differ`,320 ` got: 123`,321 `expected: 126`,322 )323 if len(missing) != 0 {324 t.Error("Following expected messages are not found:\n-", strings.Join(missing, "\n- "))325 t.Error("================================ in:")326 t.Error(strings.Join(mockT.Messages, "\n"))327 t.Error("====================================")328 }329 })330 t.Run("AssertRequire success", func(t *testing.T) {331 mockT := test.NewTestingTB("TestCodeCustom")332 td.Cmp(mockT, got, td.Map(map[string]int{}, td.MapEntries{333 "foo": td.Code(func(assert, require *td.T, n int) {334 assert.Cmp(n, 123)335 require.Cmp(n, 123)336 }),337 }))338 test.EqualInt(t, len(mockT.Messages), 0)339 })340 t.Run("AssertRequire failure", func(t *testing.T) {341 mockT := test.NewTestingTB("TestCodeCustom")342 td.NewT(mockT).343 RootName("PIPO").344 Cmp(got, td.Map(map[string]int{}, td.MapEntries{345 "foo": td.Code(func(assert, require *td.T, n int) {346 assert.Cmp(n, 124) // inherit only RootName347 assert.RootName(assert.Config.OriginalPath()).Cmp(n, 125) // recover current path348 assert.RootName(require.Config.OriginalPath()).Cmp(n, 126) // recover current path349 assert.RootName("").Cmp(n, 127) // undo RootName inheritance350 }),351 }))352 test.IsTrue(t, mockT.HasFailed)353 test.IsFalse(t, mockT.IsFatal)354 missing := mockT.ContainsMessages(355 `PIPO: values differ`,356 ` got: 123`,357 `expected: 124`,358 `PIPO["foo"]: values differ`,359 ` got: 123`,360 `expected: 125`,361 `PIPO["foo"]: values differ`,362 ` got: 123`,363 `expected: 126`,364 `DATA: values differ`,365 ` got: 123`,366 `expected: 127`,367 )368 if len(missing) != 0 {369 t.Error("Following expected messages are not found:\n-", strings.Join(missing, "\n- "))370 t.Error("================================ in:")371 t.Error(strings.Join(mockT.Messages, "\n"))372 t.Error("====================================")373 }374 })375 t.Run("AssertRequire fatalfailure", func(t *testing.T) {376 mockT := test.NewTestingTB("TestCodeCustom")377 td.NewT(mockT).378 RootName("PIPO").379 Cmp(got, td.Map(map[string]int{}, td.MapEntries{380 "foo": td.Code(func(assert, require *td.T, n int) {381 mockT.CatchFatal(func() {382 assert.RootName("FIRST").Cmp(n, 124)383 require.RootName("SECOND").Cmp(n, 125)384 assert.RootName("THIRD").Cmp(n, 126)385 })386 }),387 }))388 test.IsTrue(t, mockT.HasFailed)389 test.IsTrue(t, mockT.IsFatal)390 missing := mockT.ContainsMessages(391 `FIRST: values differ`,392 ` got: 123`,393 `expected: 124`,394 `SECOND: values differ`,395 ` got: 123`,396 `expected: 125`,397 )398 mesgs := strings.Join(mockT.Messages, "\n")399 if len(missing) != 0 {400 t.Error("Following expected messages are not found:\n-", strings.Join(missing, "\n- "))401 t.Error("================================ in:")402 t.Error(mesgs)403 t.Error("====================================")404 }405 if strings.Contains(mesgs, "THIRD") {406 t.Error("THIRD test found, but shouldn't, in:")407 t.Error(mesgs)408 t.Error("====================================")409 }410 })411}412func TestCodeTypeBehind(t *testing.T) {413 // Type behind is the code function parameter one414 equalTypes(t, td.Code(func(n int) bool { return n != 0 }), 23)415 equalTypes(t, td.Code(func(_ *td.T, n int) {}), 23)416 equalTypes(t, td.Code(func(_, _ *td.T, n int) {}), 23)417 type MyTime time.Time418 equalTypes(t,419 td.Code(func(t MyTime) bool { return time.Time(t).IsZero() }),420 MyTime{})421 equalTypes(t, td.Code(func(_ *td.T, t MyTime) {}), MyTime{})422 equalTypes(t, td.Code(func(_, _ *td.T, t MyTime) {}), MyTime{})423 // Erroneous op424 equalTypes(t, td.Code(nil), nil)425}...
TestCode
Using AI Code Generation
1import "fmt"2import "test"3func main() {4 td := new(test.TestData)5 fmt.Println(td.TestCode())6}7import "fmt"8import "test"9func main() {10 td := new(test.TestData)11 fmt.Println(td.TestCode())12}13import "fmt"14import "test"15func main() {16 td := new(test.TestData)17 fmt.Println(td.TestCode())18}19import "fmt"20import "test"21func main() {22 td := new(test.TestData)23 fmt.Println(td.TestCode())24}25import "fmt"26import "test"27func main() {28 td := new(test.TestData)29 fmt.Println(td.TestCode())30}31import "fmt"32import "test"33func main() {34 td := new(test.TestData)35 fmt.Println(td.TestCode())36}37import "fmt"38import "test"39func main() {40 td := new(test.TestData)41 fmt.Println(td.TestCode())42}43import "fmt"44import "test"45func main() {46 td := new(test.TestData)47 fmt.Println(td.TestCode())48}49import "fmt"50import "test"51func main() {52 td := new(test.TestData)53 fmt.Println(td.TestCode())54}55import "fmt"56import "test"57func main() {58 td := new(test.TestData)59 fmt.Println(td.TestCode())60}
TestCode
Using AI Code Generation
1import (2func main() {3 t := td_test.TestCode{}4 t.TestCode()5 fmt.Println("End of main")6}7import (8func main() {9 t := td_test.TestCode{}10 t.TestCode()11 fmt.Println("End of main")12}13import (14func main() {15 t := td_test.TestCode{}16 t.TestCode()17 fmt.Println("End of main")18}19import (20func main() {21 t := td_test.TestCode{}22 t.TestCode()23 fmt.Println("End of main")24}25import (26func main() {27 t := td_test.TestCode{}28 t.TestCode()29 fmt.Println("End of main")30}31import (32func main() {33 t := td_test.TestCode{}34 t.TestCode()35 fmt.Println("End of main")36}37import (38func main() {39 t := td_test.TestCode{}40 t.TestCode()41 fmt.Println("End of main")42}
TestCode
Using AI Code Generation
1import (2func main() {3 t := td_test.TestCode{}4 t.TestCode()5 fmt.Println("Hello World")6}
TestCode
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 td_test.TestCode()5}6import (7func main() {8 fmt.Println("Hello, playground")9 td_test.TestCode()10}11import (12func main() {13 fmt.Println("Hello, playground")14 td_test.TestCode()15}16import (17func main() {18 fmt.Println("Hello, playground")19 td_test.TestCode()20}21import (22func main() {23 fmt.Println("Hello, playground")24 td_test.TestCode()25}26import (27func main() {28 fmt.Println("Hello, playground")29 td_test.TestCode()30}31import (32func main() {33 fmt.Println("Hello, playground")34 td_test.TestCode()35}36import (37func main() {38 fmt.Println("Hello, playground")39 td_test.TestCode()40}41import (42func main() {43 fmt.Println("Hello, playground")44 td_test.TestCode()45}46import (
TestCode
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 td.Test()5}6import (7type TestCode struct {8}9func (td *TestCode) Test() {10 fmt.Println("Test")11}
TestCode
Using AI Code Generation
1import (2func main() {3 obj.TestCode()4 fmt.Println("TestCode Method is called")5}6import (7func main() {8 obj.TestCode()9 fmt.Println("TestCode Method is called")10}11import (12func main() {13 obj.TestCode()14 fmt.Println("TestCode Method is called")15}16import (17func main() {18 obj.TestCode()19 fmt.Println("TestCode Method is called")20}21import (22func main() {23 obj.TestCode()24 fmt.Println("TestCode Method is called")25}26import (27func main() {28 obj.TestCode()29 fmt.Println("TestCode Method is called")30}31import (32func main() {33 obj.TestCode()34 fmt.Println("TestCode Method is called")35}36import (37func main() {38 obj.TestCode()39 fmt.Println("TestCode Method is called")40}41import (42func main() {43 obj.TestCode()44 fmt.Println("TestCode Method is called")45}
TestCode
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 t = td_test.TestCode{1, "Test"}5 t.TestCodeMethod()6}7Your name to display (optional):8Your name to display (optional):
TestCode
Using AI Code Generation
1import (2func main() {3 fmt.Println(td_test.TestCode())4}5The above code is working fine. But if I change the package name to td_test2 and change the import path in 2.go to td_test2, the code is not working. I am getting the below error:6 /usr/local/go/src/td_test2 (from $GOROOT)7 /home/ashish/go/src/td_test2 (from $GOPATH)
TestCode
Using AI Code Generation
1import (2func main() {3 fmt.Println(td_test.TestCode())4}5The above code is the simplest way to use the package. You can also import the package in your code and use the function. The code will look like this:6import (7func main() {8 fmt.Println(td_test.TestCode())9}10You can also import the package in your code and use the function. The code will look like this:11import (12func main() {13 fmt.Println(td_test.TestCode())14}15The above code is the simplest way to use the package. You can also import the package in your code and use the function. The code will look like this:16import (17func main() {18 fmt.Println(td_test.TestCode())19}20The above code is the simplest way to use the package. You can also import the package in your code and use the function. The code will look like this:21import (22func main() {23 fmt.Println(td_test.TestCode())24}25The above code is the simplest way to use the package. You can also import the package in your code and use the function. The code will look like this:26import (27func main() {28 fmt.Println(td_test.TestCode())29}30The above code is the simplest way to use the package. You can also import the package in your code and use the function. The code will look like this:31import (32func main() {33 fmt.Println(td_test.TestCode())34}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!