@@ -18,12 +18,10 @@ func TestNumericDate(t *testing.T) {
18
18
19
19
jwt .TimePrecision = time .Microsecond
20
20
21
- raw := `{"iat":1516239022,"exp":1516239022.12345 }`
21
+ raw := `{"iat":1516239022.000000 ,"exp":1516239022.123450 }`
22
22
23
- err := json .Unmarshal ([]byte (raw ), & s )
24
-
25
- if err != nil {
26
- t .Errorf ("Unexpected error: %s" , err )
23
+ if err := json .Unmarshal ([]byte (raw ), & s ); err != nil {
24
+ t .Fatalf ("Unexpected error: %s" , err )
27
25
}
28
26
29
27
b , _ := json .Marshal (s )
@@ -65,3 +63,49 @@ func TestSingleArrayMarshal(t *testing.T) {
65
63
t .Errorf ("Serialized format of string array mismatch. Expecting: %s Got: %s" , string (expected ), string (b ))
66
64
}
67
65
}
66
+
67
+ func TestNumericDate_MarshalJSON (t * testing.T ) {
68
+ // Do not run this test in parallel because it's changing
69
+ // global state.
70
+ oldPrecision := jwt .TimePrecision
71
+ t .Cleanup (func () {
72
+ jwt .TimePrecision = oldPrecision
73
+ })
74
+
75
+ tt := []struct {
76
+ in time.Time
77
+ want string
78
+ precision time.Duration
79
+ }{
80
+ {time .Unix (5243700879 , 0 ), "5243700879" , time .Second },
81
+ {time .Unix (5243700879 , 0 ), "5243700879.000" , time .Millisecond },
82
+ {time .Unix (5243700879 , 0 ), "5243700879.000001" , time .Microsecond },
83
+ {time .Unix (5243700879 , 0 ), "5243700879.000000954" , time .Nanosecond },
84
+ //
85
+ {time .Unix (4239425898 , 0 ), "4239425898" , time .Second },
86
+ {time .Unix (4239425898 , 0 ), "4239425898.000" , time .Millisecond },
87
+ {time .Unix (4239425898 , 0 ), "4239425898.000000" , time .Microsecond },
88
+ {time .Unix (4239425898 , 0 ), "4239425898.000000000" , time .Nanosecond },
89
+ //
90
+ {time .Unix (0 , 1644285000210402000 ), "1644285000" , time .Second },
91
+ {time .Unix (0 , 1644285000210402000 ), "1644285000.210" , time .Millisecond },
92
+ {time .Unix (0 , 1644285000210402000 ), "1644285000.210402" , time .Microsecond },
93
+ {time .Unix (0 , 1644285000210402000 ), "1644285000.210402012" , time .Nanosecond },
94
+ //
95
+ {time .Unix (0 , 1644285315063096000 ), "1644285315" , time .Second },
96
+ {time .Unix (0 , 1644285315063096000 ), "1644285315.063" , time .Millisecond },
97
+ {time .Unix (0 , 1644285315063096000 ), "1644285315.063096" , time .Microsecond },
98
+ {time .Unix (0 , 1644285315063096000 ), "1644285315.063096046" , time .Nanosecond },
99
+ }
100
+
101
+ for i , tc := range tt {
102
+ jwt .TimePrecision = tc .precision
103
+ by , err := jwt .NewNumericDate (tc .in ).MarshalJSON ()
104
+ if err != nil {
105
+ t .Fatal (err )
106
+ }
107
+ if got := string (by ); got != tc .want {
108
+ t .Errorf ("[%d]: failed encoding: got %q want %q" , i , got , tc .want )
109
+ }
110
+ }
111
+ }
0 commit comments