github.com/abayer/test-infra@v0.0.5/boskos/common/common_test.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package common 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "reflect" 23 "testing" 24 ) 25 26 type fakeStruct struct { 27 Value string `json:"value"` 28 } 29 30 func TestUserData_Extract(t *testing.T) { 31 ud := UserData{} 32 fs := fakeStruct{"value"} 33 if err := ud.Set("test", &fs); err != nil { 34 t.Errorf("unable to set data") 35 } 36 var rfs fakeStruct 37 if err := ud.Extract("test", &rfs); err != nil { 38 t.Error("unable to extract struct") 39 } 40 if fs.Value != rfs.Value { 41 t.Error("struct don't match") 42 } 43 } 44 45 func TestUserData_Update(t *testing.T) { 46 ud1 := UserDataFromMap(UserDataMap{"0": "0"}) 47 ud2 := UserDataFromMap(UserDataMap{"1": "1", "2": "2"}) 48 ud3 := UserDataFromMap(UserDataMap{"0": "0", "1": "1", "2": "2"}) 49 ud1.Update(ud2) 50 if !reflect.DeepEqual(ud1.ToMap(), ud3.ToMap()) { 51 t.Errorf("%v does not match expected %v", ud1, ud3) 52 } 53 // Testing delete 54 ud3.Update(UserDataFromMap(UserDataMap{"0": ""})) 55 if !reflect.DeepEqual(ud3.ToMap(), ud2.ToMap()) { 56 t.Errorf("%v does not match expected %v", ud3, ud2) 57 } 58 } 59 60 func TestUserData_Marshall(t *testing.T) { 61 ud := UserDataFromMap(UserDataMap{"0": "0", "1": "1", "2": "2"}) 62 b, err := ud.MarshalJSON() 63 if err != nil { 64 t.Errorf("unable to marshall %v", ud.ToMap()) 65 } 66 var udFromJSON UserData 67 if err := udFromJSON.UnmarshalJSON(b); err != nil { 68 t.Errorf("unable to unmarshall %v", string(b)) 69 } 70 if !reflect.DeepEqual(ud.ToMap(), udFromJSON.ToMap()) { 71 t.Errorf("src %v does not match %v", ud.ToMap(), udFromJSON.ToMap()) 72 } 73 } 74 75 func TestUserData_JSON(t *testing.T) { 76 ud := UserDataFromMap(UserDataMap{"0": "0", "1": "1", "2": "2"}) 77 b := new(bytes.Buffer) 78 if err := json.NewEncoder(b).Encode(ud); err != nil { 79 t.Errorf("unable to marshall %v", ud.ToMap()) 80 } 81 var decodedUD UserData 82 if err := json.NewDecoder(b).Decode(&decodedUD); err != nil { 83 t.Errorf("unable to unmarshall %v", b.String()) 84 } 85 86 if !reflect.DeepEqual(ud.ToMap(), decodedUD.ToMap()) { 87 t.Errorf("src %v does not match %v", ud.ToMap(), decodedUD.ToMap()) 88 } 89 90 }