tstime/rate: implement Value.{Marshal,Unmarshal}JSON (#8481)

Implement support for marshaling and unmarshaling a Value.

Updates tailscale/corp#8427

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
Joe Tsai
2024-01-16 13:48:34 -08:00
committed by GitHub
parent 1c3c3d6752
commit 7732377cd7
2 changed files with 64 additions and 0 deletions

View File

@@ -6,12 +6,14 @@ package rate
import (
"flag"
"math"
"reflect"
"testing"
"time"
qt "github.com/frankban/quicktest"
"github.com/google/go-cmp/cmp/cmpopts"
"tailscale.com/tstime/mono"
"tailscale.com/util/must"
)
const (
@@ -234,3 +236,26 @@ func BenchmarkValue(b *testing.B) {
v.Add(1)
}
}
func TestValueMarshal(t *testing.T) {
now := mono.Now()
tests := []struct {
val *Value
str string
}{
{val: &Value{}, str: `{}`},
{val: &Value{HalfLife: 5 * time.Minute}, str: `{"halfLife":"` + (5 * time.Minute).String() + `"}`},
{val: &Value{value: 12345, updated: now}, str: `{"value":12345,"updated":` + string(must.Get(now.MarshalJSON())) + `}`},
}
for _, tt := range tests {
str := string(must.Get(tt.val.MarshalJSON()))
if str != tt.str {
t.Errorf("string mismatch: got %v, want %v", str, tt.str)
}
var val Value
must.Do(val.UnmarshalJSON([]byte(str)))
if !reflect.DeepEqual(&val, tt.val) {
t.Errorf("value mismatch: %+v, want %+v", &val, tt.val)
}
}
}