github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/helper/raftutil/msgpack_test.go (about) 1 package raftutil 2 3 import ( 4 "bytes" 5 "fmt" 6 "testing" 7 "time" 8 9 "github.com/hashicorp/go-msgpack/codec" 10 "github.com/hashicorp/nomad/nomad/structs" 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestMaybeDecodeTimeIgnoresASCII(t *testing.T) { 15 cases := []string{ 16 "127.0.0.1/32", 17 "host", 18 } 19 20 for _, c := range cases { 21 t.Run(c, func(t *testing.T) { 22 tt, err := maybeDecodeTime(c) 23 fmt.Println(tt) 24 require.Nil(t, tt) 25 require.Error(t, err) 26 }) 27 } 28 } 29 30 func TestDecodesTime(t *testing.T) { 31 type Value struct { 32 CreateTime time.Time 33 Mode string 34 } 35 now := time.Now().Truncate(time.Second) 36 v := Value{ 37 CreateTime: now, 38 Mode: "host", 39 } 40 41 var buf bytes.Buffer 42 err := codec.NewEncoder(&buf, structs.MsgpackHandle).Encode(v) 43 require.NoError(t, err) 44 45 var r map[string]interface{} 46 err = codec.NewDecoder(&buf, structs.MsgpackHandle).Decode(&r) 47 require.NoError(t, err) 48 49 require.Equal(t, "host", r["Mode"]) 50 require.IsType(t, "", r["CreateTime"]) 51 52 fixTime(r) 53 54 expected := map[string]interface{}{ 55 "CreateTime": now, 56 "Mode": "host", 57 } 58 require.Equal(t, expected, r) 59 } 60 61 func TestMyDate(t *testing.T) { 62 handler := &codec.MsgpackHandle{} 63 handler.TimeNotBuiltin = true 64 65 d := time.Date(2025, 7, 10, 8, 1, 56, 0, time.UTC) 66 67 var buf bytes.Buffer 68 err := codec.NewEncoder(&buf, handler).Encode(d) 69 require.NoError(t, err) 70 71 var s string 72 err = codec.NewDecoder(&buf, handler).Decode(&s) 73 require.NoError(t, err) 74 75 fmt.Printf("Original: %q\nround trips: %q\n", d, s) 76 }