github.com/argoproj/argo-events@v1.9.1/pkg/apis/common/int64str_test.go (about) 1 package common 2 3 import ( 4 "encoding/json" 5 "reflect" 6 "testing" 7 8 "sigs.k8s.io/yaml" 9 ) 10 11 func TestFromInt64(t *testing.T) { 12 i := FromInt64(93) 13 if i.Type != Int64 || i.Int64Val != 93 { 14 t.Errorf("Expected Int64Val=93, got %+v", i) 15 } 16 } 17 18 func TestFromString(t *testing.T) { 19 i := FromString("76") 20 if i.Type != String || i.StrVal != "76" { 21 t.Errorf("Expected StrVal=\"76\", got %+v", i) 22 } 23 } 24 25 type Int64OrStringHolder struct { 26 IOrS Int64OrString `json:"val"` 27 } 28 29 func TestInt64OrStringUnmarshalJSON(t *testing.T) { 30 cases := []struct { 31 input string 32 result Int64OrString 33 }{ 34 {"{\"val\": 123}", FromInt64(123)}, 35 {"{\"val\": \"123\"}", FromString("123")}, 36 } 37 38 for _, c := range cases { 39 var result Int64OrStringHolder 40 if err := json.Unmarshal([]byte(c.input), &result); err != nil { 41 t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) 42 } 43 if result.IOrS != c.result { 44 t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) 45 } 46 } 47 } 48 49 func TestInt64OrStringMarshalJSON(t *testing.T) { 50 cases := []struct { 51 input Int64OrString 52 result string 53 }{ 54 {FromInt64(123), "{\"val\":123}"}, 55 {FromString("123"), "{\"val\":\"123\"}"}, 56 } 57 58 for _, c := range cases { 59 input := Int64OrStringHolder{c.input} 60 result, err := json.Marshal(&input) 61 if err != nil { 62 t.Errorf("Failed to marshal input '%v': %v", input, err) 63 } 64 if string(result) != c.result { 65 t.Errorf("Failed to marshal input '%v': expected: %+v, got %q", input, c.result, string(result)) 66 } 67 } 68 } 69 70 func TestInt64OrStringMarshalJSONUnmarshalYAML(t *testing.T) { 71 cases := []struct { 72 input Int64OrString 73 }{ 74 {FromInt64(123)}, 75 {FromString("123")}, 76 } 77 78 for _, c := range cases { 79 input := Int64OrStringHolder{c.input} 80 jsonMarshalled, err := json.Marshal(&input) 81 if err != nil { 82 t.Errorf("1: Failed to marshal input: '%v': %v", input, err) 83 } 84 85 var result Int64OrStringHolder 86 err = yaml.Unmarshal(jsonMarshalled, &result) 87 if err != nil { 88 t.Errorf("2: Failed to unmarshal '%+v': %v", string(jsonMarshalled), err) 89 } 90 91 if !reflect.DeepEqual(input, result) { 92 t.Errorf("3: Failed to marshal input '%+v': got %+v", input, result) 93 } 94 } 95 }