github.com/searKing/golang/go@v1.2.117/time/convert_test.go (about) 1 // Copyright 2021 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package time_test 6 7 import ( 8 "testing" 9 "time" 10 11 time_ "github.com/searKing/golang/go/time" 12 ) 13 14 func TestConvertTimestamp(t *testing.T) { 15 now := time.Now() 16 tests := []struct { 17 timestamp int64 18 fromUnit time.Duration 19 toUnit time.Duration 20 wantTimestamp int64 21 }{ 22 { 23 timestamp: now.Unix(), 24 fromUnit: time.Second, 25 toUnit: time.Nanosecond, 26 wantTimestamp: now.Unix() * int64(time.Second/time.Nanosecond), 27 }, 28 { 29 timestamp: now.UnixNano(), 30 fromUnit: time.Nanosecond, 31 toUnit: time.Second, 32 wantTimestamp: now.Unix(), 33 }, 34 } 35 for i, tt := range tests { 36 gotTimestamp := time_.ConvertTimestamp(tt.timestamp, tt.fromUnit, tt.toUnit) 37 if tt.wantTimestamp != gotTimestamp { 38 t.Errorf("#%d: ConvertTimestamp expected %q got %q", i, tt.wantTimestamp, gotTimestamp) 39 } 40 } 41 } 42 43 func TestTimestamp(t *testing.T) { 44 now := time.Now() 45 tests := []struct { 46 timestamp time.Time 47 unit time.Duration 48 wantTimestamp int64 49 }{ 50 { 51 timestamp: now, 52 unit: time.Second, 53 wantTimestamp: now.Unix(), 54 }, 55 { 56 timestamp: now, 57 unit: time.Millisecond, 58 wantTimestamp: now.UnixNano() * int64(time.Nanosecond) / int64(time.Millisecond), 59 }, 60 { 61 timestamp: now, 62 unit: time.Nanosecond, 63 wantTimestamp: now.UnixNano(), 64 }, 65 { 66 timestamp: now, 67 unit: time.Second, 68 wantTimestamp: now.Unix(), 69 }, 70 } 71 for i, tt := range tests { 72 gotTimestamp := time_.Timestamp(tt.timestamp, tt.unit) 73 if tt.wantTimestamp != gotTimestamp { 74 t.Errorf("#%d: ConvertTimestamp expected %d got %d", i, tt.wantTimestamp, gotTimestamp) 75 } 76 } 77 } 78 79 func TestUnixWithUnit(t *testing.T) { 80 now := time.Now() 81 tests := []struct { 82 timestamp int64 83 unit time.Duration 84 wantTime time.Time 85 }{ 86 { 87 timestamp: now.Unix(), 88 unit: time.Second, 89 wantTime: time.Unix(now.Unix(), 0), 90 }, 91 { 92 timestamp: now.UnixNano(), 93 unit: time.Nanosecond, 94 wantTime: time.Unix(0, now.UnixNano()), 95 }, 96 } 97 for i, tt := range tests { 98 gotTimestamp := time_.UnixWithUnit(tt.timestamp, tt.unit) 99 if tt.wantTime != gotTimestamp { 100 t.Errorf("#%d: ConvertTimestamp expected %q got %q", i, tt.wantTime, gotTimestamp) 101 } 102 } 103 }