MCPcopy Index your code
hub / github.com/segmentio/encoding / TestCodecDuration

Function TestCodecDuration

json/json_test.go:428–496  ·  view source on GitHub ↗

TestCodecDuration isolates testing of time.Duration. The stdlib un/marshals this type as integers whereas this library un/marshals formatted string values. Therefore, plugging durations into TestCodec would cause fail since it checks equality on the marshaled strings from the two libraries.

(t *testing.T)

Source from the content-addressed store, hash-verified

426// values. Therefore, plugging durations into TestCodec would cause fail since
427// it checks equality on the marshaled strings from the two libraries.
428func TestCodecDuration(t *testing.T) {
429 for _, v1 := range durationTestValues {
430 t.Run(testName(v1), func(t *testing.T) {
431 v2 := newValue(v1)
432
433 // encode using stdlib. (will be an int)
434 std, err := json.MarshalIndent(v1, "", "\t")
435 if err != nil {
436 t.Error(err)
437 return
438 }
439 std = append(std, '\n')
440
441 // decode using our decoder. (reads int to duration)
442 dec := NewDecoder(bytes.NewBuffer([]byte(std)))
443
444 if err := dec.Decode(v2.Interface()); err != nil {
445 t.Errorf("%T: %v", err, err)
446 return
447 }
448
449 x1 := v1
450 x2 := v2.Elem().Interface()
451
452 if !reflect.DeepEqual(x1, x2) {
453 t.Error("values mismatch")
454 t.Logf("expected: %#v", x1)
455 t.Logf("found: %#v", x2)
456 }
457
458 // encoding using our encoder. (writes duration as string)
459 buf := &bytes.Buffer{}
460 enc := NewEncoder(buf)
461 enc.SetIndent("", "\t")
462
463 if err := enc.Encode(v1); err != nil {
464 t.Error(err)
465 return
466 }
467 b := buf.Bytes()
468
469 if !Valid(b) {
470 t.Error("invalid JSON representation")
471 }
472
473 if reflect.DeepEqual(std, b) {
474 t.Error("encoded durations should not match stdlib")
475 t.Logf("got: %s", b)
476 }
477
478 // decode using our decoder. (reads string to duration)
479 dec = NewDecoder(bytes.NewBuffer([]byte(std)))
480
481 if err := dec.Decode(v2.Interface()); err != nil {
482 t.Errorf("%T: %v", err, err)
483 return
484 }
485

Callers

nothing calls this directly

Calls 11

DecodeMethod · 0.95
SetIndentMethod · 0.95
EncodeMethod · 0.95
testNameFunction · 0.85
newValueFunction · 0.85
BytesMethod · 0.80
NewDecoderFunction · 0.70
NewEncoderFunction · 0.70
ValidFunction · 0.70
ElemMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…