github.com/psiphon-inc/goarista@v0.0.0-20160825065156-d002785f4c67/key/stringify_test.go (about) 1 // Copyright (C) 2015 Arista Networks, Inc. 2 // Use of this source code is governed by the Apache License 2.0 3 // that can be found in the COPYING file. 4 5 package key 6 7 import ( 8 "math" 9 "testing" 10 ) 11 12 func TestStringify(t *testing.T) { 13 testcases := []struct { 14 name string 15 input interface{} 16 output string // or expected panic error message. 17 }{{ 18 name: "nil", 19 input: nil, 20 output: "Unable to stringify nil", 21 }, { 22 name: "struct{}", 23 input: struct{}{}, 24 output: "Unable to stringify type struct {}: struct {}{}", 25 }, { 26 name: "string", 27 input: "foobar", 28 output: "foobar", 29 }, { 30 name: "uint8", 31 input: uint8(43), 32 output: "43", 33 }, { 34 name: "uint16", 35 input: uint16(43), 36 output: "43", 37 }, { 38 name: "uint32", 39 input: uint32(43), 40 output: "43", 41 }, { 42 name: "uint64", 43 input: uint64(43), 44 output: "43", 45 }, { 46 name: "max uint64", 47 input: uint64(math.MaxUint64), 48 output: "18446744073709551615", 49 }, { 50 name: "int8", 51 input: int8(-32), 52 output: "-32", 53 }, { 54 name: "int16", 55 input: int16(-32), 56 output: "-32", 57 }, { 58 name: "int32", 59 input: int32(-32), 60 output: "-32", 61 }, { 62 name: "int64", 63 input: int64(-32), 64 output: "-32", 65 }, { 66 name: "true", 67 input: true, 68 output: "true", 69 }, { 70 name: "false", 71 input: false, 72 output: "false", 73 }, { 74 name: "float32", 75 input: float32(2.345), 76 output: "f1075188859", 77 }, { 78 name: "float64", 79 input: float64(-34.6543), 80 output: "f-4593298060402564373", 81 }, { 82 name: "map[string]interface{}", 83 input: map[string]interface{}{ 84 "b": uint32(43), 85 "a": "foobar", 86 "ex": map[string]interface{}{ 87 "d": "barfoo", 88 "c": uint32(45), 89 }, 90 }, 91 output: "foobar_43_45_barfoo", 92 }, { 93 name: "map[Key]interface{}", 94 input: map[Key]interface{}{ 95 New(uint32(42)): true, 96 New("foo"): "bar", 97 New(map[string]interface{}{"hello": "world"}): "yolo", 98 }, 99 output: "42=true_foo=bar_world=yolo", 100 }, { 101 name: "nil inside map[string]interface{}", 102 input: map[string]interface{}{ 103 "n": nil, 104 }, 105 output: "Unable to stringify nil", 106 }} 107 108 for _, tcase := range testcases { 109 // Pardon the contraption used to catch panic's in error cases. 110 func() { 111 defer func() { 112 if e := recover(); e != nil { 113 if tcase.output != e.(error).Error() { 114 t.Errorf("Test %s: Error returned: %q but wanted %q", 115 tcase.name, e, tcase.output) 116 } 117 } 118 }() 119 120 result := stringify(tcase.input) 121 if tcase.output != result { 122 t.Errorf("Test %s: Result is different\nReceived: %s\nExpected: %s", 123 tcase.name, result, tcase.output) 124 } 125 }() 126 } 127 }