1// Copyright 2014 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package datastore
16
17import (
18	"testing"
19	"time"
20)
21
22func TestUnixMicro(t *testing.T) {
23	// Test that all these time.Time values survive a round trip to unix micros.
24	testCases := []time.Time{
25		{},
26		time.Date(2, 1, 1, 0, 0, 0, 0, time.UTC),
27		time.Date(23, 1, 1, 0, 0, 0, 0, time.UTC),
28		time.Date(234, 1, 1, 0, 0, 0, 0, time.UTC),
29		time.Date(1000, 1, 1, 0, 0, 0, 0, time.UTC),
30		time.Date(1600, 1, 1, 0, 0, 0, 0, time.UTC),
31		time.Date(1700, 1, 1, 0, 0, 0, 0, time.UTC),
32		time.Date(1800, 1, 1, 0, 0, 0, 0, time.UTC),
33		time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC),
34		time.Unix(-1e6, -1000),
35		time.Unix(-1e6, 0),
36		time.Unix(-1e6, +1000),
37		time.Unix(-60, -1000),
38		time.Unix(-60, 0),
39		time.Unix(-60, +1000),
40		time.Unix(-1, -1000),
41		time.Unix(-1, 0),
42		time.Unix(-1, +1000),
43		time.Unix(0, -3000),
44		time.Unix(0, -2000),
45		time.Unix(0, -1000),
46		time.Unix(0, 0),
47		time.Unix(0, +1000),
48		time.Unix(0, +2000),
49		time.Unix(+60, -1000),
50		time.Unix(+60, 0),
51		time.Unix(+60, +1000),
52		time.Unix(+1e6, -1000),
53		time.Unix(+1e6, 0),
54		time.Unix(+1e6, +1000),
55		time.Date(1999, 12, 31, 23, 59, 59, 999000, time.UTC),
56		time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
57		time.Date(2006, 1, 2, 15, 4, 5, 678000, time.UTC),
58		time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC),
59		time.Date(3456, 1, 1, 0, 0, 0, 0, time.UTC),
60	}
61	for _, tc := range testCases {
62		got := fromUnixMicro(toUnixMicro(tc))
63		if !got.Equal(tc) {
64			t.Errorf("got %q, want %q", got, tc)
65		}
66	}
67
68	// Test that a time.Time that isn't an integral number of microseconds
69	// is not perfectly reconstructed after a round trip.
70	t0 := time.Unix(0, 123)
71	t1 := fromUnixMicro(toUnixMicro(t0))
72	if t1.Nanosecond()%1000 != 0 || t0.Nanosecond()%1000 == 0 {
73		t.Errorf("quantization to µs: got %q with %d ns, started with %d ns", t1, t1.Nanosecond(), t0.Nanosecond())
74	}
75}
76