|
| 1 | +package paseto |
| 2 | + |
| 3 | +import ( |
| 4 | + "strconv" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func TestNumericDateMarshal(t *testing.T) { |
| 10 | + now := time.Now() |
| 11 | + nowTS := now.Unix() |
| 12 | + |
| 13 | + testCases := []struct { |
| 14 | + value *NumericDate |
| 15 | + want string |
| 16 | + }{ |
| 17 | + {NewNumericDate(time.Time{}), `null`}, |
| 18 | + {NewNumericDate(now), strconv.Itoa(int(nowTS))}, |
| 19 | + } |
| 20 | + |
| 21 | + for _, tc := range testCases { |
| 22 | + raw, err := tc.value.MarshalJSON() |
| 23 | + mustOk(t, err) |
| 24 | + mustEqual(t, string(raw), tc.want) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func TestNumericDateUnmarshal(t *testing.T) { |
| 29 | + testCases := []struct { |
| 30 | + s string |
| 31 | + want NumericDate |
| 32 | + }{ |
| 33 | + {`1588707274`, asNumericDate(1588707274)}, |
| 34 | + {`1588707274.3769999`, asNumericDate(1588707274)}, |
| 35 | + {`"12345"`, asNumericDate(12345)}, |
| 36 | + } |
| 37 | + |
| 38 | + for _, tc := range testCases { |
| 39 | + var have NumericDate |
| 40 | + err := have.UnmarshalJSON([]byte(tc.s)) |
| 41 | + mustOk(t, err) |
| 42 | + mustEqual(t, have.Unix(), tc.want.Unix()) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func TestNumericDateUnmarshalMalformed(t *testing.T) { |
| 47 | + testCases := []struct { |
| 48 | + value string |
| 49 | + }{ |
| 50 | + {``}, |
| 51 | + {`{}`}, |
| 52 | + {`[{}]`}, |
| 53 | + {`abc12`}, |
| 54 | + {`"abc"`}, |
| 55 | + {`["admin",{}]`}, |
| 56 | + {`["admin",123]`}, |
| 57 | + {`{}`}, |
| 58 | + {`[]`}, |
| 59 | + {`1e+309`}, |
| 60 | + } |
| 61 | + |
| 62 | + for _, tc := range testCases { |
| 63 | + var nd NumericDate |
| 64 | + err := nd.UnmarshalJSON([]byte(tc.value)) |
| 65 | + mustFail(t, err) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +func asNumericDate(n int64) NumericDate { |
| 70 | + return *NewNumericDate(time.Unix(n, 0)) |
| 71 | +} |
0 commit comments