2023-02-07 06:48:12 +03:00
|
|
|
package time
|
|
|
|
|
|
|
|
import (
|
2023-02-13 14:02:08 +03:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2023-02-07 06:48:12 +03:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-02-13 14:02:08 +03:00
|
|
|
func TestMarshalJSON(t *testing.T) {
|
|
|
|
d := Duration(10000000)
|
|
|
|
buf, err := json.Marshal(d)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if !bytes.Equal(buf, []byte(`"10ms"`)) {
|
|
|
|
t.Fatalf("invalid duration: %s != %s", buf, `"10ms"`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestUnmarshalJSON(t *testing.T) {
|
|
|
|
type str struct {
|
|
|
|
TTL Duration `json:"ttl"`
|
|
|
|
}
|
|
|
|
v := &str{}
|
2023-05-29 13:59:30 +03:00
|
|
|
var err error
|
2023-02-13 14:02:08 +03:00
|
|
|
|
2023-05-29 13:59:30 +03:00
|
|
|
err = json.Unmarshal([]byte(`{"ttl":"10ms"}`), v)
|
2023-02-13 14:02:08 +03:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
} else if v.TTL != 10000000 {
|
|
|
|
t.Fatalf("invalid duration %v != 10000000", v.TTL)
|
|
|
|
}
|
2023-05-29 13:59:30 +03:00
|
|
|
|
|
|
|
err = json.Unmarshal([]byte(`{"ttl":"1y"}`), v)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
2024-03-09 17:21:20 +03:00
|
|
|
} else if v.TTL != 31622400000000000 {
|
2023-05-29 13:59:30 +03:00
|
|
|
t.Fatalf("invalid duration %v != 31536000000000000", v.TTL)
|
|
|
|
}
|
2023-02-13 14:02:08 +03:00
|
|
|
}
|
|
|
|
|
2023-02-07 06:48:12 +03:00
|
|
|
func TestParseDuration(t *testing.T) {
|
|
|
|
var td time.Duration
|
|
|
|
var err error
|
2023-05-27 23:55:08 +03:00
|
|
|
|
2023-02-07 06:48:12 +03:00
|
|
|
td, err = ParseDuration("14d4h")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("ParseDuration error: %v", err)
|
|
|
|
}
|
2023-05-27 23:55:08 +03:00
|
|
|
if td.String() != "340h0m0s" {
|
|
|
|
t.Fatalf("ParseDuration 14d != 340h0m0s : %s", td.String())
|
2023-02-07 06:48:12 +03:00
|
|
|
}
|
|
|
|
td, err = ParseDuration("1y")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("ParseDuration error: %v", err)
|
|
|
|
}
|
2024-03-09 17:21:20 +03:00
|
|
|
if td.String() != "8784h0m0s" {
|
2023-02-07 06:48:12 +03:00
|
|
|
t.Fatalf("ParseDuration 1y != 8760h0m0s : %s", td.String())
|
|
|
|
}
|
|
|
|
}
|