timestamp_test.mx raw
1 package timestamp
2
3 import (
4 "encoding/binary"
5 "testing"
6 "time"
7 )
8
9 func TestNewAndAccessors(t *testing.T) {
10 tv := New(1700000000)
11 if tv.I64() != 1700000000 || tv.U64() != 1700000000 || tv.Int() != 1700000000 {
12 t.Fatal("New accessors disagree")
13 }
14 if tv.Time().Unix() != 1700000000 {
15 t.Fatal("Time")
16 }
17 if tv.String() != "1700000000" {
18 t.Fatalf("String: got %s", tv.String())
19 }
20 var nilT *T
21 if nilT.U64() != 0 || nilT.I64() != 0 || nilT.Int() != 0 {
22 t.Fatal("a nil timestamp should read as zero")
23 }
24 }
25
26 func TestBytesRoundTrip(t *testing.T) {
27 tv := New(1700000000)
28 back := FromBytes(tv.Bytes())
29 if back.I64() != tv.I64() {
30 t.Fatal("Bytes/FromBytes roundtrip")
31 }
32 }
33
34 func TestMarshalUnmarshal(t *testing.T) {
35 tv := New(1700000000)
36 buf := tv.Marshal(nil)
37 if string(buf) != "1700000000" {
38 t.Fatalf("Marshal: got %s", string(buf))
39 }
40 back := New(0)
41 rem, err := back.Unmarshal(buf)
42 if err != nil {
43 t.Fatal(err)
44 }
45 if back.I64() != 1700000000 || len(rem) != 0 {
46 t.Fatal("Unmarshal")
47 }
48 js, err := tv.MarshalJSON()
49 if err != nil {
50 t.Fatal(err)
51 }
52 if string(js) != "1700000000" {
53 t.Fatalf("MarshalJSON: got %s", string(js))
54 }
55 }
56
57 // TestFromVarint pins the encoding FromVarint decodes: it reads Go's zigzag
58 // varint (encoding/binary), one value, and hands back what follows it.
59 func TestFromVarint(t *testing.T) {
60 b := []byte{:11}
61 n := binary.PutVarint(b, 300)
62 b[n] = 0xff
63 tv, rem, err := FromVarint(b[:n+1])
64 if err != nil {
65 t.Fatal(err)
66 }
67 if tv.I64() != 300 {
68 t.Fatalf("value: got %d", tv.I64())
69 }
70 if string(rem) != string([]byte{0xff}) {
71 t.Fatal("remainder should be the byte after the varint")
72 }
73 if _, _, err = FromVarint(nil); err == nil {
74 t.Fatal("an empty varint should fail")
75 }
76 }
77
78 func TestConversions(t *testing.T) {
79 if FromTime(time.Unix(1700000001, 0)).I64() != 1700000001 {
80 t.Fatal("FromTime")
81 }
82 if FromUnix(1700000002).I64() != 1700000002 {
83 t.Fatal("FromUnix")
84 }
85 var tv T
86 tv.FromInt(7)
87 if tv.I64() != 7 {
88 t.Fatal("FromInt")
89 }
90 if Now().I64() < 1600000000 {
91 t.Fatal("Now is not a unix timestamp")
92 }
93 }
94