github.com/newrelic/newrelic-client-go@v1.1.0/internal/serialization/epoch_time_test.go (about) 1 //go:build unit 2 // +build unit 3 4 package serialization 5 6 import ( 7 "strconv" 8 "testing" 9 "time" 10 11 "github.com/stretchr/testify/assert" 12 ) 13 14 var testEpochValues = []struct { 15 Bytes []byte 16 Epoch EpochTime 17 String string 18 Unix int64 19 Err error 20 Msg string 21 }{ 22 { 23 Bytes: []byte(`1587654321`), // Seconds 24 Epoch: EpochTime(time.Unix(1587654321, 0).UTC()), 25 String: "2020-04-23 15:05:21 +0000 UTC", 26 Unix: 1587654321, 27 Err: nil, 28 Msg: "Epoch: Seconds", 29 }, 30 { 31 Bytes: []byte(`1587654321012`), // Milliseconds 32 Epoch: EpochTime(time.Unix(1587654321, 12*int64(time.Millisecond)).UTC()), 33 String: "2020-04-23 15:05:21.012 +0000 UTC", 34 Unix: 1587654321, 35 Err: nil, 36 Msg: "Epoch: Millieconds", 37 }, 38 { 39 Bytes: []byte(`1587654321012345678`), // Nanoseconds 40 Epoch: EpochTime(time.Unix(1587654321, 12345).UTC()), 41 String: "2020-04-23 15:05:21.000012345 +0000 UTC", 42 Unix: 1587654321, 43 Err: nil, 44 Msg: "Epoch: Nanoseconds", 45 }, 46 { 47 Bytes: []byte(`asdf`), // Invalid 48 Epoch: EpochTime{}, 49 String: "0001-01-01 00:00:00 +0000 UTC", 50 Unix: 0, 51 Err: &strconv.NumError{}, 52 Msg: "Epoch: invalid", 53 }, 54 } 55 56 func TestEpochUnmarshal(t *testing.T) { 57 t.Parallel() 58 59 for _, v := range testEpochValues { 60 var et EpochTime 61 err := et.UnmarshalJSON(v.Bytes) 62 63 if v.Err != nil { 64 assert.Error(t, err) 65 } else { 66 assert.NoError(t, err) 67 } 68 assert.Equal(t, v.Epoch, et, v.Msg) 69 } 70 } 71 72 func TestEpochMarshalJSON(t *testing.T) { 73 t.Parallel() 74 75 for _, v := range testEpochValues { 76 var et EpochTime 77 err := et.UnmarshalJSON(v.Bytes) 78 79 if v.Err != nil { 80 assert.Error(t, err) 81 } else { 82 assert.NoError(t, err) 83 } 84 assert.Equal(t, v.Epoch, et, v.Msg) 85 } 86 } 87 88 func TestEpochString(t *testing.T) { 89 t.Parallel() 90 91 for _, v := range testEpochValues { 92 if v.Err == nil { 93 res := v.Epoch.String() 94 assert.Equal(t, v.String, res, v.Msg) 95 } 96 } 97 } 98 99 func TestEpochUnix(t *testing.T) { 100 t.Parallel() 101 102 for _, v := range testEpochValues { 103 if v.Err == nil { 104 res := v.Epoch.Unix() 105 assert.Equal(t, v.Unix, res, v.Msg) 106 } 107 } 108 }