mirror of
https://github.com/tailscale/tailscale.git
synced 2025-08-15 07:27:30 +00:00
tstime: add GoDuration which JSON serializes with time.Duration.String (#15726)
The encoding/json/v2 effort may end up changing the default represention of time.Duration in JSON. See https://go.dev/issue/71631 The GoDuration type allows us to explicitly use the time.Duration.String representation regardless of whether we serialize with v1 or v2 of encoding/json. Updates tailscale/corp#27502 Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
@@ -4,8 +4,11 @@
|
||||
package tstime
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"tailscale.com/util/must"
|
||||
)
|
||||
|
||||
func TestParseDuration(t *testing.T) {
|
||||
@@ -34,3 +37,17 @@ func TestParseDuration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoDuration(t *testing.T) {
|
||||
wantDur := GoDuration{time.Hour + time.Minute + time.Second + time.Millisecond + time.Microsecond + time.Nanosecond}
|
||||
gotJSON := string(must.Get(json.Marshal(wantDur)))
|
||||
wantJSON := `"1h1m1.001001001s"`
|
||||
if gotJSON != wantJSON {
|
||||
t.Errorf("json.Marshal(%v) = %s, want %s", wantDur, gotJSON, wantJSON)
|
||||
}
|
||||
var gotDur GoDuration
|
||||
must.Do(json.Unmarshal([]byte(wantJSON), &gotDur))
|
||||
if gotDur != wantDur {
|
||||
t.Errorf("json.Unmarshal(%s) = %v, want %v", wantJSON, gotDur, wantDur)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user