Best Go-testdeep code snippet using td_test.TestJSON
td_json_test.go
Source:td_json_test.go
...18// Read implements io.Reader.19func (r errReader) Read(p []byte) (int, error) {20 return 0, errors.New("an error occurred")21}22func TestJSON(t *testing.T) {23 type MyStruct struct {24 Name string `json:"name"`25 Age uint `json:"age"`26 Gender string `json:"gender"`27 }28 //29 // nil30 checkOK(t, nil, td.JSON(`null`))31 checkOK(t, (*int)(nil), td.JSON(`null`))32 //33 // Basic types34 checkOK(t, 123, td.JSON(` 123 `))35 checkOK(t, true, td.JSON(` true `))36 checkOK(t, false, td.JSON(` false `))37 checkOK(t, "foobar", td.JSON(` "foobar" `))38 //39 // struct40 //41 got := MyStruct{Name: "Bob", Age: 42, Gender: "male"}42 // No placeholder43 checkOK(t, got,44 td.JSON(`{"name":"Bob","age":42,"gender":"male"}`))45 checkOK(t, got, td.JSON(`$1`, got)) // json.Marshal() got for $146 // Numeric placeholders47 checkOK(t, got,48 td.JSON(`{"name":"$1","age":$2,"gender":$3}`,49 "Bob", 42, "male")) // raw values50 checkOK(t, got,51 td.JSON(`{"name":"$1","age":$2,"gender":"$3"}`,52 td.Re(`^Bob`),53 td.Between(40, 45),54 td.NotEmpty()))55 // Same using Flatten56 checkOK(t, got,57 td.JSON(`{"name":"$1","age":$2,"gender":"$3"}`,58 td.Re(`^Bob`),59 td.Flatten([]td.TestDeep{td.Between(40, 45), td.NotEmpty()}),60 ))61 // Operators are not JSON marshallable62 checkOK(t, got,63 td.JSON(`$1`, map[string]any{64 "name": td.Re(`^Bob`),65 "age": 42,66 "gender": td.NotEmpty(),67 }))68 // Placeholder + unmarshal before comparison69 checkOK(t, json.RawMessage(`[1,2,3]`), td.JSON(`$1`, []int{1, 2, 3}))70 checkOK(t, json.RawMessage(`{"foo":[1,2,3]}`),71 td.JSON(`{"foo":$1}`, []int{1, 2, 3}))72 checkOK(t, json.RawMessage(`[1,2,3]`),73 td.JSON(`$1`, []any{1, td.Between(1, 3), 3}))74 // Tag placeholders75 checkOK(t, got,76 td.JSON(`{"name":"$name","age":$age,"gender":$gender}`,77 // raw values78 td.Tag("name", "Bob"), td.Tag("age", 42), td.Tag("gender", "male")))79 checkOK(t, got,80 td.JSON(`{"name":"$name","age":$age,"gender":"$gender"}`,81 td.Tag("name", td.Re(`^Bo`)),82 td.Tag("age", td.Between(40, 45)),83 td.Tag("gender", td.NotEmpty())))84 // Tag placeholders + operators are not JSON marshallable85 checkOK(t, got,86 td.JSON(`$all`, td.Tag("all", map[string]any{87 "name": td.Re(`^Bob`),88 "age": 42,89 "gender": td.NotEmpty(),90 })))91 // Tag placeholders + nil92 checkOK(t, nil, td.JSON(`$all`, td.Tag("all", nil)))93 // Mixed placeholders + operator94 for _, op := range []string{95 "NotEmpty",96 "NotEmpty()",97 "$^NotEmpty",98 "$^NotEmpty()",99 `"$^NotEmpty"`,100 `"$^NotEmpty()"`,101 `r<$^NotEmpty>`,102 `r<$^NotEmpty()>`,103 } {104 checkOK(t, got,105 td.JSON(`{"name":"$name","age":$1,"gender":`+op+`}`,106 td.Tag("age", td.Between(40, 45)),107 td.Tag("name", td.Re(`^Bob`))),108 "using operator %s", op)109 }110 checkOK(t, got,111 td.JSON(`{"name":Re("^Bo\\w"),"age":Between(40,45),"gender":NotEmpty()}`))112 checkOK(t, got,113 td.JSON(`114{115 "name": All(Re("^Bo\\w"), HasPrefix("Bo"), HasSuffix("ob")),116 "age": Between(40,45),117 "gender": NotEmpty()118}`))119 checkOK(t, got,120 td.JSON(`121{122 "name": All(Re("^Bo\\w"), HasPrefix("Bo"), HasSuffix("ob")),123 "age": Between(40,45),124 "gender": NotEmpty125}`))126 // Same but operators in strings using "$^"127 checkOK(t, got,128 td.JSON(`{"name":Re("^Bo\\w"),"age":"$^Between(40,45)","gender":"$^NotEmpty()"}`))129 checkOK(t, got, // using classic "" string, so each \ has to be escaped130 td.JSON(`131{132 "name": "$^All(Re(\"^Bo\\\\w\"), HasPrefix(\"Bo\"), HasSuffix(\"ob\"))",133 "age": "$^Between(40,45)",134 "gender": "$^NotEmpty()",135}`))136 checkOK(t, got, // using raw strings, no escape needed137 td.JSON(`138{139 "name": "$^All(Re(r(^Bo\\w)), HasPrefix(r{Bo}), HasSuffix(r'ob'))",140 "age": "$^Between(40,45)",141 "gender": "$^NotEmpty()",142}`))143 // â¦with commentsâ¦144 checkOK(t, got,145 td.JSON(`146// This should be the JSON representation of MyStruct struct147{148 // A person:149 "name": "$name", // The name of this person150 "age": $1, /* The age of this person:151 - placeholder unquoted, but could be without152 any change153 - to demonstrate a multi-lines comment */154 "gender": $^NotEmpty // Operator NotEmpty155}`,156 td.Tag("age", td.Between(40, 45)),157 td.Tag("name", td.Re(`^Bob`))))158 before := time.Now()159 timeGot := map[string]time.Time{"created_at": time.Now()}160 checkOK(t, timeGot,161 td.JSON(`{"created_at": Between($1, $2)}`, before, time.Now()))162 checkOK(t, timeGot,163 td.JSON(`{"created_at": $1}`, td.Between(before, time.Now())))164 // Len165 checkOK(t, []int{1, 2, 3}, td.JSON(`Len(3)`))166 //167 // []byte168 checkOK(t, got,169 td.JSON([]byte(`{"name":"$name","age":$1,"gender":"male"}`),170 td.Tag("age", td.Between(40, 45)),171 td.Tag("name", td.Re(`^Bob`))))172 //173 // nil++174 checkOK(t, nil, td.JSON(`$1`, nil))175 checkOK(t, (*int)(nil), td.JSON(`$1`, td.Nil()))176 checkOK(t, nil, td.JSON(`$x`, td.Tag("x", nil)))177 checkOK(t, (*int)(nil), td.JSON(`$x`, td.Tag("x", nil)))178 checkOK(t, json.RawMessage(`{"foo": null}`), td.JSON(`{"foo": null}`))179 checkOK(t,180 json.RawMessage(`{"foo": null}`),181 td.JSON(`{"foo": $1}`, nil))182 checkOK(t,183 json.RawMessage(`{"foo": null}`),184 td.JSON(`{"foo": $1}`, td.Nil()))185 checkOK(t,186 json.RawMessage(`{"foo": null}`),187 td.JSON(`{"foo": $x}`, td.Tag("x", nil)))188 checkOK(t,189 json.RawMessage(`{"foo": null}`),190 td.JSON(`{"foo": $x}`, td.Tag("x", td.Nil())))191 //192 // Loading a file193 tmpDir := t.TempDir()194 filename := tmpDir + "/test.json"195 err := os.WriteFile(196 filename, []byte(`{"name":$name,"age":$1,"gender":$^NotEmpty}`), 0644)197 if err != nil {198 t.Fatal(err)199 }200 checkOK(t, got,201 td.JSON(filename,202 td.Tag("age", td.Between(40, 45)),203 td.Tag("name", td.Re(`^Bob`))))204 //205 // Reading (a file)206 tmpfile, err := os.Open(filename)207 if err != nil {208 t.Fatal(err)209 }210 checkOK(t, got,211 td.JSON(tmpfile,212 td.Tag("age", td.Between(40, 45)),213 td.Tag("name", td.Re(`^Bob`))))214 tmpfile.Close()215 //216 // Escaping $ in strings217 checkOK(t, "$test", td.JSON(`"$$test"`))218 //219 // Errors220 checkError(t, func() {}, td.JSON(`null`),221 expectedError{222 Message: mustBe("json.Marshal failed"),223 Summary: mustContain("json: unsupported type"),224 })225 checkError(t, map[string]string{"zip": "pipo"},226 td.All(td.JSON(`SuperMapOf({"zip":$1})`, "bingo")),227 expectedError{228 Path: mustBe(`DATA`),229 Message: mustBe("compared (part 1 of 1)"),230 Got: mustBe(`(map[string]string) (len=1) {231 (string) (len=3) "zip": (string) (len=4) "pipo"232}`),233 Expected: mustBe(`JSON(SuperMapOf(map[string]interface {}{234 "zip": "bingo",235 }))`),236 Origin: &expectedError{237 Path: mustBe(`DATA<All#1/1>["zip"]`),238 Message: mustBe(`values differ`),239 Got: mustBe(`"pipo"`),240 Expected: mustBe(`"bingo"`),241 },242 })243 //244 // Fatal errors245 checkError(t, "never tested",246 td.JSON("uNkNoWnFiLe.json"),247 expectedError{248 Message: mustBe("bad usage of JSON operator"),249 Path: mustBe("DATA"),250 Summary: mustContain("JSON file uNkNoWnFiLe.json cannot be read: "),251 })252 checkError(t, "never tested",253 td.JSON(42),254 expectedError{255 Message: mustBe("bad usage of JSON operator"),256 Path: mustBe("DATA"),257 Summary: mustBe("usage: JSON(STRING_JSON|STRING_FILENAME|[]byte|io.Reader, ...), but received int as 1st parameter"),258 })259 checkError(t, "never tested",260 td.JSON(errReader{}),261 expectedError{262 Message: mustBe("bad usage of JSON operator"),263 Path: mustBe("DATA"),264 Summary: mustBe("JSON read error: an error occurred"),265 })266 checkError(t, "never tested",267 td.JSON(`pipo`),268 expectedError{269 Message: mustBe("bad usage of JSON operator"),270 Path: mustBe("DATA"),271 Summary: mustContain("JSON unmarshal error: "),272 })273 checkError(t, "never tested",274 td.JSON(`[$foo]`,275 td.Tag("foo", td.Ignore()),276 td.Tag("foo", td.Ignore())),277 expectedError{278 Message: mustBe("bad usage of JSON operator"),279 Path: mustBe("DATA"),280 Summary: mustBe(`2 params have the same tag "foo"`),281 })282 checkError(t, []int{42},283 td.JSON(`[$1]`, func() {}),284 expectedError{285 Message: mustBe("an error occurred while unmarshalling JSON into func()"),286 Path: mustBe("DATA[0]"),287 Summary: mustBe("json: cannot unmarshal number into Go value of type func()"),288 })289 checkError(t, []int{42},290 td.JSON(`[$foo]`, td.Tag("foo", func() {})),291 expectedError{292 Message: mustBe("an error occurred while unmarshalling JSON into func()"),293 Path: mustBe("DATA[0]"),294 Summary: mustBe("json: cannot unmarshal number into Go value of type func()"),295 })296 // numeric placeholders297 checkError(t, "never tested",298 td.JSON(`[1, "$123bad"]`),299 expectedError{300 Message: mustBe("bad usage of JSON operator"),301 Path: mustBe("DATA"),302 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder at line 1:5 (pos 5)`),303 })304 checkError(t, "never tested",305 td.JSON(`[1, $000]`),306 expectedError{307 Message: mustBe("bad usage of JSON operator"),308 Path: mustBe("DATA"),309 Summary: mustBe(`JSON unmarshal error: invalid numeric placeholder "$000", it should start at "$1" at line 1:4 (pos 4)`),310 })311 checkError(t, "never tested",312 td.JSON(`[1, $1]`),313 expectedError{314 Message: mustBe("bad usage of JSON operator"),315 Path: mustBe("DATA"),316 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$1", but no params given at line 1:4 (pos 4)`),317 })318 checkError(t, "never tested",319 td.JSON(`[1, 2, $3]`, td.Ignore()),320 expectedError{321 Message: mustBe("bad usage of JSON operator"),322 Path: mustBe("DATA"),323 Summary: mustBe(`JSON unmarshal error: numeric placeholder "$3", but only one param given at line 1:7 (pos 7)`),324 })325 // $^Operator326 checkError(t, "never tested",327 td.JSON(`[1, $^bad%]`),328 expectedError{329 Message: mustBe("bad usage of JSON operator"),330 Path: mustBe("DATA"),331 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:4 (pos 4)`),332 })333 checkError(t, "never tested",334 td.JSON(`[1, "$^bad%"]`),335 expectedError{336 Message: mustBe("bad usage of JSON operator"),337 Path: mustBe("DATA"),338 Summary: mustBe(`JSON unmarshal error: $^ must be followed by an operator name at line 1:5 (pos 5)`),339 })340 // named placeholders341 checkError(t, "never tested",342 td.JSON(`[343 1,344 "$bad%"345]`),346 expectedError{347 Message: mustBe("bad usage of JSON operator"),348 Path: mustBe("DATA"),349 Summary: mustBe(`JSON unmarshal error: bad placeholder "$bad%" at line 3:3 (pos 10)`),350 })351 checkError(t, "never tested",352 td.JSON(`[1, $unknown]`),353 expectedError{354 Message: mustBe("bad usage of JSON operator"),355 Path: mustBe("DATA"),356 Summary: mustBe(`JSON unmarshal error: unknown placeholder "$unknown" at line 1:4 (pos 4)`),357 })358 //359 // Stringification360 test.EqualStr(t, td.JSON(`1`).String(),361 `JSON(1)`)362 test.EqualStr(t, td.JSON(`[ 1, 2, 3 ]`).String(),363 `364JSON([365 1,366 2,367 3368 ])`[1:])369 test.EqualStr(t, td.JSON(` null `).String(), `JSON(null)`)370 test.EqualStr(t,371 td.JSON(`[ $1, $name, $2, Nil(), $nil, 26, Between(5, 6), Len(34), Len(Between(5, 6)), 28 ]`,372 td.Between(12, 20),373 "test",374 td.Tag("name", td.Code(func(s string) bool { return len(s) > 0 })),375 td.Tag("nil", nil),376 14,377 ).String(),378 `379JSON([380 "$1" /* 12 ⤠got ⤠20 */,381 "$name" /* Code(func(string) bool) */,382 "test",383 nil,384 null,385 26,386 5.0 ⤠got ⤠6.0,387 len=34,388 len: 5.0 ⤠got ⤠6.0,389 28390 ])`[1:])391 test.EqualStr(t,392 td.JSON(`[ $1, $name, $2, $^Nil, $nil ]`,393 td.Between(12, 20),394 "test",395 td.Tag("name", td.Code(func(s string) bool { return len(s) > 0 })),396 td.Tag("nil", nil),397 ).String(),398 `399JSON([400 "$1" /* 12 ⤠got ⤠20 */,401 "$name" /* Code(func(string) bool) */,402 "test",403 nil,404 null405 ])`[1:])406 test.EqualStr(t,407 td.JSON(`{"label": $value, "zip": $^NotZero}`,408 td.Tag("value", td.Bag(409 td.JSON(`{"name": $1,"age":$2,"surname":$3}`,410 td.HasPrefix("Bob"),411 td.Between(12, 24),412 "captain",413 ),414 td.JSON(`{"name": $1}`, td.HasPrefix("Alice")),415 )),416 ).String(),417 `418JSON({419 "label": "$value" /* Bag(JSON({420 "age": "$2" /* 12 ⤠got ⤠24 */,421 "name": "$1" /* HasPrefix("Bob") */,422 "surname": "captain"423 }),424 JSON({425 "name": "$1" /* HasPrefix("Alice") */426 })) */,427 "zip": NotZero()428 })`[1:])429 test.EqualStr(t,430 td.JSON(`431{432 "label": {"name": HasPrefix("Bob"), "age": Between(12,24)},433 "zip": NotZero()434}`).String(),435 `436JSON({437 "label": {438 "age": 12.0 ⤠got ⤠24.0,439 "name": HasPrefix("Bob")440 },441 "zip": NotZero()442 })`[1:])443 // Erroneous op444 test.EqualStr(t, td.JSON(`[`).String(), "JSON(<ERROR>)")445}446func TestJSONInside(t *testing.T) {447 // Between448 t.Run("Between", func(t *testing.T) {449 got := map[string]int{"val1": 1, "val2": 2}450 checkOK(t, got,451 td.JSON(`{"val1": Between(0, 2), "val2": Between(2, 3, "[[")}`))452 checkOK(t, got,453 td.JSON(`{"val1": Between(0, 2), "val2": Between(2, 3, "BoundsInOut")}`))454 for _, bounds := range []string{"[[", "BoundsInOut"} {455 checkError(t, got,456 td.JSON(`{"val1": Between(0, 2), "val2": Between(1, 2, $1)}`, bounds),457 expectedError{458 Message: mustBe("values differ"),459 Path: mustBe(`DATA["val2"]`),460 Got: mustBe("2.0"),461 Expected: mustBe("1.0 ⤠got < 2.0"),462 })463 }464 checkOK(t, got,465 td.JSON(`{"val1": Between(1, 1), "val2": Between(2, 2, "[]")}`))466 checkOK(t, got,467 td.JSON(`{"val1": Between(1, 1), "val2": Between(2, 2, "BoundsInIn")}`))468 checkOK(t, got,469 td.JSON(`{"val1": Between(0, 1, "]]"), "val2": Between(1, 3, "][")}`))470 checkOK(t, got,471 td.JSON(`{"val1": Between(0, 1, "BoundsOutIn"), "val2": Between(1, 3, "BoundsOutOut")}`))472 for _, bounds := range []string{"]]", "BoundsOutIn"} {473 checkError(t, got,474 td.JSON(`{"val1": 1, "val2": Between(2, 3, $1)}`, bounds),475 expectedError{476 Message: mustBe("values differ"),477 Path: mustBe(`DATA["val2"]`),478 Got: mustBe("2.0"),479 Expected: mustBe("2.0 < got ⤠3.0"),480 })481 }482 for _, bounds := range []string{"][", "BoundsOutOut"} {483 checkError(t, got,484 td.JSON(`{"val1": 1, "val2": Between(2, 3, $1)}`, bounds),485 expectedError{486 Message: mustBe("values differ"),487 Path: mustBe(`DATA["val2"]`),488 Got: mustBe("2.0"),489 Expected: mustBe("2.0 < got < 3.0"),490 },491 "using bounds %q", bounds)492 checkError(t, got,493 td.JSON(`{"val1": 1, "val2": Between(1, 2, $1)}`, bounds),494 expectedError{495 Message: mustBe("values differ"),496 Path: mustBe(`DATA["val2"]`),497 Got: mustBe("2.0"),498 Expected: mustBe("1.0 < got < 2.0"),499 },500 "using bounds %q", bounds)501 }502 // Bad 3rd parameter503 checkError(t, "never tested",504 td.JSON(`{505 "val2": Between(1, 2, "<>")506}`),507 expectedError{508 Message: mustBe("bad usage of JSON operator"),509 Path: mustBe("DATA"),510 Summary: mustBe(`JSON unmarshal error: Between() bad 3rd parameter, use "[]", "[[", "]]" or "][" at line 2:10 (pos 12)`),511 })512 checkError(t, "never tested",513 td.JSON(`{514 "val2": Between(1, 2, 125)515}`),516 expectedError{517 Message: mustBe("bad usage of JSON operator"),518 Path: mustBe("DATA"),519 Summary: mustBe(`JSON unmarshal error: Between() bad 3rd parameter, use "[]", "[[", "]]" or "][" at line 2:10 (pos 12)`),520 })521 checkError(t, "never tested",522 td.JSON(`{"val2": Between(1)}`),523 expectedError{524 Message: mustBe("bad usage of JSON operator"),525 Path: mustBe("DATA"),526 Summary: mustBe(`JSON unmarshal error: Between() requires 2 or 3 parameters at line 1:9 (pos 9)`),527 })528 checkError(t, "never tested",529 td.JSON(`{"val2": Between(1,2,3,4)}`),530 expectedError{531 Message: mustBe("bad usage of JSON operator"),532 Path: mustBe("DATA"),533 Summary: mustBe(`JSON unmarshal error: Between() requires 2 or 3 parameters at line 1:9 (pos 9)`),534 })535 })536 // N537 t.Run("N", func(t *testing.T) {538 got := map[string]float32{"val": 2.1}539 checkOK(t, got, td.JSON(`{"val": N(2.1)}`))540 checkOK(t, got, td.JSON(`{"val": N(2, 0.1)}`))541 checkError(t, "never tested",542 td.JSON(`{"val2": N()}`),543 expectedError{544 Message: mustBe("bad usage of JSON operator"),545 Path: mustBe("DATA"),546 Summary: mustBe(`JSON unmarshal error: N() requires 1 or 2 parameters at line 1:9 (pos 9)`),547 })548 checkError(t, "never tested",549 td.JSON(`{"val2": N(1,2,3)}`),550 expectedError{551 Message: mustBe("bad usage of JSON operator"),552 Path: mustBe("DATA"),553 Summary: mustBe(`JSON unmarshal error: N() requires 1 or 2 parameters at line 1:9 (pos 9)`),554 })555 })556 // Re557 t.Run("Re", func(t *testing.T) {558 got := map[string]string{"val": "Foo bar"}559 checkOK(t, got, td.JSON(`{"val": Re("^Foo")}`))560 checkOK(t, got, td.JSON(`{"val": Re("^(\\w+)", ["Foo"])}`))561 checkOK(t, got, td.JSON(`{"val": Re("^(\\w+)", Bag("Foo"))}`))562 checkError(t, "never tested",563 td.JSON(`{"val2": Re()}`),564 expectedError{565 Message: mustBe("bad usage of JSON operator"),566 Path: mustBe("DATA"),567 Summary: mustBe(`JSON unmarshal error: Re() requires 1 or 2 parameters at line 1:9 (pos 9)`),568 })569 checkError(t, "never tested",570 td.JSON(`{"val2": Re(1,2,3)}`),571 expectedError{572 Message: mustBe("bad usage of JSON operator"),573 Path: mustBe("DATA"),574 Summary: mustBe(`JSON unmarshal error: Re() requires 1 or 2 parameters at line 1:9 (pos 9)`),575 })576 })577 // SubMapOf578 t.Run("SubMapOf", func(t *testing.T) {579 got := []map[string]int{{"val1": 1, "val2": 2}}580 checkOK(t, got, td.JSON(`[ SubMapOf({"val1":1, "val2":2, "xxx": "yyy"}) ]`))581 checkError(t, "never tested",582 td.JSON(`[ SubMapOf() ]`),583 expectedError{584 Message: mustBe("bad usage of JSON operator"),585 Path: mustBe("DATA"),586 Summary: mustBe(`JSON unmarshal error: SubMapOf() requires only one parameter at line 1:2 (pos 2)`),587 })588 checkError(t, "never tested",589 td.JSON(`[ SubMapOf(1, 2) ]`),590 expectedError{591 Message: mustBe("bad usage of JSON operator"),592 Path: mustBe("DATA"),593 Summary: mustBe(`JSON unmarshal error: SubMapOf() requires only one parameter at line 1:2 (pos 2)`),594 })595 })596 // SuperMapOf597 t.Run("SuperMapOf", func(t *testing.T) {598 got := []map[string]int{{"val1": 1, "val2": 2}}599 checkOK(t, got, td.JSON(`[ SuperMapOf({"val1":1}) ]`))600 checkError(t, "never tested",601 td.JSON(`[ SuperMapOf() ]`),602 expectedError{603 Message: mustBe("bad usage of JSON operator"),604 Path: mustBe("DATA"),605 Summary: mustBe(`JSON unmarshal error: SuperMapOf() requires only one parameter at line 1:2 (pos 2)`),606 })607 checkError(t, "never tested",608 td.JSON(`[ SuperMapOf(1, 2) ]`),609 expectedError{610 Message: mustBe("bad usage of JSON operator"),611 Path: mustBe("DATA"),612 Summary: mustBe(`JSON unmarshal error: SuperMapOf() requires only one parameter at line 1:2 (pos 2)`),613 })614 })615 // errors616 t.Run("Errors", func(t *testing.T) {617 checkError(t, "never tested",618 td.JSON(`[ UnknownOp() ]`),619 expectedError{620 Message: mustBe("bad usage of JSON operator"),621 Path: mustBe("DATA"),622 Summary: mustBe(`JSON unmarshal error: unknown operator UnknownOp() at line 1:2 (pos 2)`),623 })624 checkError(t, "never tested",625 td.JSON(`[ Catch() ]`),626 expectedError{627 Message: mustBe("bad usage of JSON operator"),628 Path: mustBe("DATA"),629 Summary: mustBe(`JSON unmarshal error: Catch() is not usable in JSON() at line 1:2 (pos 2)`),630 })631 checkError(t, "never tested",632 td.JSON(`[ JSON() ]`),633 expectedError{634 Message: mustBe("bad usage of JSON operator"),635 Path: mustBe("DATA"),636 Summary: mustBe(`JSON unmarshal error: JSON() is not usable in JSON(), use literal JSON instead at line 1:2 (pos 2)`),637 })638 checkError(t, "never tested",639 td.JSON(`[ All() ]`),640 expectedError{641 Message: mustBe("bad usage of JSON operator"),642 Path: mustBe("DATA"),643 Summary: mustBe(`JSON unmarshal error: All() requires at least one parameter at line 1:2 (pos 2)`),644 })645 checkError(t, "never tested",646 td.JSON(`[ Empty(12) ]`),647 expectedError{648 Message: mustBe("bad usage of JSON operator"),649 Path: mustBe("DATA"),650 Summary: mustBe(`JSON unmarshal error: Empty() requires no parameters at line 1:2 (pos 2)`),651 })652 checkError(t, "never tested",653 td.JSON(`[ HasPrefix() ]`),654 expectedError{655 Message: mustBe("bad usage of JSON operator"),656 Path: mustBe("DATA"),657 Summary: mustBe(`JSON unmarshal error: HasPrefix() requires only one parameter at line 1:2 (pos 2)`),658 })659 checkError(t, "never tested",660 td.JSON(`[ JSONPointer(1, 2, 3) ]`),661 expectedError{662 Message: mustBe("bad usage of JSON operator"),663 Path: mustBe("DATA"),664 Summary: mustBe(`JSON unmarshal error: JSONPointer() requires 2 parameters at line 1:2 (pos 2)`),665 })666 checkError(t, "never tested",667 td.JSON(`[ JSONPointer(1, 2) ]`),668 expectedError{669 Message: mustBe("bad usage of JSON operator"),670 Path: mustBe("DATA"),671 Summary: mustBe(`JSON unmarshal error: JSONPointer() bad #1 parameter type: string required but float64 received at line 1:2 (pos 2)`),672 })673 // This one is not caught by JSON, but by Re itself, as the number674 // of parameters is correct675 checkError(t, json.RawMessage(`"never tested"`),676 td.JSON(`Re(1)`),677 expectedError{678 Message: mustBe("bad usage of Re operator"),679 Path: mustBe("DATA"),680 Summary: mustBe(`usage: Re(STRING|*regexp.Regexp[, NON_NIL_CAPTURE]), but received float64 as 1st parameter`),681 })682 })683}684func TestJSONTypeBehind(t *testing.T) {685 equalTypes(t, td.JSON(`false`), true)686 equalTypes(t, td.JSON(`"foo"`), "")687 equalTypes(t, td.JSON(`42`), float64(0))688 equalTypes(t, td.JSON(`[1,2,3]`), ([]any)(nil))689 equalTypes(t, td.JSON(`{"a":12}`), (map[string]any)(nil))690 // operator at the root â delegate it TypeBehind() call691 equalTypes(t, td.JSON(`$1`, td.SuperMapOf(map[string]any{"x": 1}, nil)), (map[string]any)(nil))692 equalTypes(t, td.JSON(`SuperMapOf({"x":1})`), (map[string]any)(nil))693 equalTypes(t, td.JSON(`$1`, 123), 42)694 nullType := td.JSON(`null`).TypeBehind()695 if nullType != reflect.TypeOf((*any)(nil)).Elem() {696 t.Errorf("Failed test: got %s intead of interface {}", nullType)697 }698 // Erroneous op...
TestJSON
Using AI Code Generation
1import (2func main() {3 c, err := redis.Dial("tcp", "localhost:6379")4 if err != nil {5 fmt.Println("Connection Error", err)6 }7 defer c.Close()8 reply, err := c.Do("TestJSON")9 if err != nil {10 fmt.Println("TestJSON Error", err)11 }12 fmt.Println("TestJSON Reply", reply)13 str, err := redis.String(reply, err)14 if err != nil {15 fmt.Println("String Conversion Error", err)16 }17 fmt.Println("TestJSON Reply as String", str)18 var f interface{}19 err = json.Unmarshal([]byte(str), &f)20 if err != nil {21 fmt.Println("JSON Conversion Error", err)22 }23 fmt.Println("TestJSON Reply as JSON", f)24}
TestJSON
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 fmt.Println(td_test)5 fmt.Println(td_test2)6 fmt.Println(tdlib)7 fmt.Println(client)8 fmt.Println(query)9 fmt.Println(message)10 fmt.Println(types)11 fmt.Println(telegram)12 fmt.Println(parse)13 fmt.Println(entities)14 fmt.Println(formatted_text)15 fmt.Println(text_entities)16 fmt.Println(text_url)17 fmt.Println(web_page)18 var jsonStr = []byte(`{"name":"Wednesday","age":6,"parents":["Gomez","Morticia"]}`)19 var data map[string]interface{}20 if err := json.Unmarshal(jsonStr, &data); err != nil {21 panic(err)22 }23 fmt.Println(data["name"])24 fmt.Println(data["age
TestJSON
Using AI Code Generation
1import (2func main() {3td.TestJSON()4fmt.Println("Done")5}6import (7func main() {8td.TestJSON()9fmt.Println("Done")10}11import (12type Td_test struct {13}14func (td *Td_test) TestJSON() {15var jsonBlob = []byte(`[16{"Name": "Platypus", "Order": "Monotremata"},17{"Name": "Quoll", "Order": "Dasyuromorphia"}18type Animal struct {19}20err := json.Unmarshal(jsonBlob, &animals)21if err != nil {22fmt.Println("error:", err)23}24fmt.Printf("%+v", animals)25}26./1.go:9: td.TestJSON undefined (type td_test.Td_test has no field or method TestJSON)27./1.go:9: td.TestJSON undefined (type td_test.Td_test has no field or method TestJSON)
TestJSON
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 td := td_test.Td_test{}5 js, err := json.Marshal(td)6 if err != nil {7 fmt.Println(err)8 }9 fmt.Println(string(js))10}11import (12func main() {13 fmt.Println("Hello, playground")14 td := td_test.Td_test{}15 js, err := json.Marshal(td)16 if err != nil {17 fmt.Println(err)18 }19 fmt.Println(string(js))20}21You need to put the package statement in the file you are building, not in the file you are importing. You should have a file named 2.go in the td_test directory, and it should start with:22import (23func main() {24 fmt.Println("Hello, playground")25 td := td_test.Td_test{}
TestJSON
Using AI Code Generation
1import (2func main() {3 fmt.Println("Starting main")4 test := td_test.NewTestStruct()5 test.TestJSON()6}7import (8func main() {9 fmt.Println("Starting main")10 test := td_test.NewTestStruct()11 test.TestJSON()12}13import (14func main() {15 fmt.Println("Starting main")16 test := td_test.NewTestStruct()17 test.TestJSON()18}19import (20func main() {21 fmt.Println("Starting main")22 test := td_test.NewTestStruct()23 test.TestJSON()24}25import (26func main() {27 fmt.Println("Starting main")28 test := td_test.NewTestStruct()29 test.TestJSON()30}31import (32func main() {33 fmt.Println("Starting main")34 test := td_test.NewTestStruct()35 test.TestJSON()36}37import (38func main() {39 fmt.Println("Starting main")40 test := td_test.NewTestStruct()41 test.TestJSON()42}43import (44func main() {45 fmt.Println("Starting main")46 test := td_test.NewTestStruct()47 test.TestJSON()48}49import (50func main() {51 fmt.Println("Starting main")52 test := td_test.NewTestStruct()53 test.TestJSON()54}55import (56func main() {57 fmt.Println("Starting main")58 test := td_test.NewTestStruct()59 test.TestJSON()60}61import (62func main() {63 fmt.Println("Starting main")64 test := td_test.NewTestStruct()65 test.TestJSON()66}67import (
TestJSON
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 td := td_test.NewTestJSON()5 td.TestJSON()6}7import (8func main() {9 fmt.Println("Hello World!")10 td := td_test.NewTestJSON()11 td.TestJSON()12}13import (14func main() {15 fmt.Println("Hello World!")16 td := td_test.NewTestJSON()17 td.TestJSON()18}19import (20func main() {21 fmt.Println("Hello World!")22 td := td_test.NewTestJSON()23 td.TestJSON()24}25import (26func main() {27 fmt.Println("Hello World!")28 td := td_test.NewTestJSON()29 td.TestJSON()30}31import (32func main() {33 fmt.Println("Hello World!")34 td := td_test.NewTestJSON()35 td.TestJSON()36}37import (38func main() {39 fmt.Println("Hello World!")40 td := td_test.NewTestJSON()41 td.TestJSON()42}43import (44func main() {45 fmt.Println("Hello World!")46 td := td_test.NewTestJSON()47 td.TestJSON()48}
TestJSON
Using AI Code Generation
1import (2func main() {3 obj := td_test.TestJSON{}4 obj.TestJSON()5 fmt.Println("done")6}7{8 { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },9 { "name":"BMW", "models":[ "320", "X3", "X5" ] },10 { "name":"Fiat", "models":[ "500", "Panda" ] }11}12import (13type Car struct {14}15type Cars struct {16}17func main() {18 jsonFile, err := os.Open("test.json")19 if err != nil {20 fmt.Println(err)21 }22 defer jsonFile.Close()23 byteValue, _ := ioutil.ReadAll(jsonFile)24 json.Unmarshal(byteValue, &cars)25 fmt.Println(cars)26}27{John [{Ford [Fiesta Focus Mustang]} {BMW [320 X3 X5]} {Fiat [500 Panda]}]}28import (29type Car struct {30}31type Cars struct {32}33func main() {34 cars := Cars{35 Cars: []Car{36 Car{Name: "Ford", Models: []string{"Fiesta", "Focus", "Mustang"}},37 Car{Name: "BMW", Models: []string{"320", "X3", "X5"}},38 Car{Name: "Fiat",
TestJSON
Using AI Code Generation
1import (2func main() {3 td, err := td_test.New()4 if err != nil {5 fmt.Println("Error initializing td_test class: ", err)6 }7 json, err := td.TestJSON()8 if err != nil {9 fmt.Println("Error: ", err)10 }11 fmt.Println("JSON: ", json)12}
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!!