|
| 1 | +package jsontypes |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "reflect" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +func ptrVal[V any](v V) *V { |
| 11 | + return &v |
| 12 | +} |
| 13 | + |
| 14 | +func TestParsingDuration(t *testing.T) { |
| 15 | + t.Parallel() |
| 16 | + type decStruct struct { |
| 17 | + Dur ParsingDuration |
| 18 | + DurPtr *ParsingDuration |
| 19 | + } |
| 20 | + for _, tbl := range []struct { |
| 21 | + name string |
| 22 | + inJSON string |
| 23 | + expStruct any |
| 24 | + expErr bool |
| 25 | + }{ |
| 26 | + { |
| 27 | + name: "integer_value_no_ptr", |
| 28 | + inJSON: `{"dur": 1234}`, |
| 29 | + expStruct: decStruct{Dur: 1234}, |
| 30 | + expErr: false, |
| 31 | + }, |
| 32 | + { |
| 33 | + name: "string_value_no_ptr", |
| 34 | + inJSON: `{"dur": "3s"}`, |
| 35 | + expStruct: decStruct{Dur: ParsingDuration(3 * time.Second)}, |
| 36 | + expErr: false, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "string_value_ptr", |
| 40 | + inJSON: `{"dur": "3s", "durptr": "9m"}`, |
| 41 | + expStruct: decStruct{Dur: ParsingDuration(3 * time.Second), DurPtr: ptrVal(ParsingDuration(9 * time.Minute))}, |
| 42 | + expErr: false, |
| 43 | + }, |
| 44 | + { |
| 45 | + name: "integer_value_ptr", |
| 46 | + inJSON: `{"dur": "3s", "durptr": 2048}`, |
| 47 | + expStruct: decStruct{Dur: ParsingDuration(3 * time.Second), DurPtr: ptrVal(ParsingDuration(2048))}, |
| 48 | + expErr: false, |
| 49 | + }, |
| 50 | + { |
| 51 | + name: "error_array_val", |
| 52 | + inJSON: `{"dur": [], "durptr": 2048}`, |
| 53 | + expErr: true, |
| 54 | + }, |
| 55 | + { |
| 56 | + name: "error_object_val", |
| 57 | + inJSON: `{"dur": {}, "durptr": 2048}`, |
| 58 | + expErr: true, |
| 59 | + }, |
| 60 | + { |
| 61 | + name: "error_unparsable_str_val", |
| 62 | + inJSON: `{"dur": "sssssssssss", "durptr": 2048}`, |
| 63 | + expErr: true, |
| 64 | + }, |
| 65 | + { |
| 66 | + name: "error_float_fractional_val", |
| 67 | + inJSON: `{"dur": 0.333333, "durptr": 2048}`, |
| 68 | + expErr: true, |
| 69 | + }, |
| 70 | + } { |
| 71 | + t.Run(tbl.name, func(t *testing.T) { |
| 72 | + v := decStruct{} |
| 73 | + decErr := json.Unmarshal([]byte(tbl.inJSON), &v) |
| 74 | + if decErr != nil { |
| 75 | + if !tbl.expErr { |
| 76 | + t.Errorf("unexpected error unmarshaling: %s", decErr) |
| 77 | + } else { |
| 78 | + t.Logf("expected error: %s", decErr) |
| 79 | + } |
| 80 | + return |
| 81 | + } |
| 82 | + if !reflect.DeepEqual(v, tbl.expStruct) { |
| 83 | + t.Errorf("unexpected value\n got: %+v\nwant:%+v", tbl.expStruct, v) |
| 84 | + } |
| 85 | + }) |
| 86 | + |
| 87 | + } |
| 88 | +} |
0 commit comments