github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/timeutil/time_test.go (about)

     1  // Copyright 2017 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package timeutil
    12  
    13  import (
    14  	"math"
    15  	"math/rand"
    16  	"testing"
    17  	"time"
    18  
    19  	"github.com/stretchr/testify/assert"
    20  )
    21  
    22  func TestUnixMicros(t *testing.T) {
    23  	testCases := []struct {
    24  		us      int64
    25  		utcTime time.Time
    26  	}{
    27  		{-1, time.Date(1969, 12, 31, 23, 59, 59, 999999000, time.UTC)},
    28  		{0, time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)},
    29  		{1, time.Date(1970, 1, 1, 0, 0, 0, 1000, time.UTC)},
    30  		{4242424242424242, time.Date(2104, 6, 9, 3, 10, 42, 424242000, time.UTC)},
    31  		{math.MaxInt64, time.Date(294247, 1, 10, 4, 0, 54, 775807000, time.UTC)},
    32  		{-62135596800000000, time.Time{}},
    33  	}
    34  	for i, testCase := range testCases {
    35  		if e, a := testCase.utcTime, FromUnixMicros(testCase.us).UTC(); e != a {
    36  			t.Errorf("%d:FromUnixMicro: expected %v, but got %v", i, e, a)
    37  		}
    38  
    39  		if e, a := testCase.us, ToUnixMicros(testCase.utcTime); e != a {
    40  			t.Errorf("%d:ToUnixMicro: expected %v, but got %v", i, e, a)
    41  		}
    42  	}
    43  
    44  	for i := 0; i < 32; i++ {
    45  		us := rand.Int63()
    46  		if e, a := us, ToUnixMicros(FromUnixMicros(us)); e != a {
    47  			t.Errorf("%d did not roundtrip; got back %d", e, a)
    48  		}
    49  	}
    50  }
    51  
    52  func TestUnixMicrosRounding(t *testing.T) {
    53  	testCases := []struct {
    54  		us      int64
    55  		utcTime time.Time
    56  	}{
    57  		{0, time.Date(1970, 1, 1, 0, 0, 0, 1, time.UTC)},
    58  		{0, time.Date(1970, 1, 1, 0, 0, 0, 499, time.UTC)},
    59  		{1, time.Date(1970, 1, 1, 0, 0, 0, 500, time.UTC)},
    60  		{1, time.Date(1970, 1, 1, 0, 0, 0, 999, time.UTC)},
    61  	}
    62  	for i, testCase := range testCases {
    63  		if e, a := testCase.us, ToUnixMicros(testCase.utcTime); e != a {
    64  			t.Errorf("%d:ToUnixMicro: expected %v, but got %v", i, e, a)
    65  		}
    66  	}
    67  }
    68  
    69  func TestReplaceLibPQTimePrefix(t *testing.T) {
    70  	assert.Equal(t, "1970-02-02 11:00", ReplaceLibPQTimePrefix("1970-02-02 11:00"))
    71  	assert.Equal(t, "1970-01-01 11:00", ReplaceLibPQTimePrefix("0000-01-01 11:00"))
    72  }