github.com/vmware/govmomi@v0.43.0/vim25/types/types_test.go (about) 1 /* 2 Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved. 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 types 18 19 import ( 20 "bytes" 21 "reflect" 22 "testing" 23 24 "github.com/stretchr/testify/assert" 25 26 "github.com/vmware/govmomi/vim25/xml" 27 ) 28 29 func TestManagedObjectReference(t *testing.T) { 30 31 testCases := []struct { 32 name string 33 obj ManagedObjectReference 34 expXML string 35 expJSON string 36 }{ 37 { 38 name: "with server GUID", 39 obj: ManagedObjectReference{ 40 Type: "fake", 41 Value: "fake", 42 ServerGUID: "fake", 43 }, 44 expXML: `<ManagedObjectReference type="fake" serverGuid="fake">fake</ManagedObjectReference>`, 45 expJSON: `{"_typeName":"ManagedObjectReference","type":"fake","value":"fake","serverGuid":"fake"}`, 46 }, 47 { 48 name: "sans server GUID", 49 obj: ManagedObjectReference{ 50 Type: "fake", 51 Value: "fake", 52 }, 53 expXML: `<ManagedObjectReference type="fake">fake</ManagedObjectReference>`, 54 expJSON: `{"_typeName":"ManagedObjectReference","type":"fake","value":"fake"}`, 55 }, 56 } 57 58 for i := range testCases { 59 tc := testCases[i] // capture the test case 60 61 t.Run(tc.name, func(t *testing.T) { 62 t.Run("xml", func(t *testing.T) { 63 act, err := xml.Marshal(tc.obj) 64 if err != nil { 65 t.Fatal(err) 66 } 67 if e, a := tc.expXML, string(act); e != a { 68 t.Fatalf("failed to marshal MoRef to XML: exp=%s, act=%s", e, a) 69 } 70 }) 71 t.Run("json", func(t *testing.T) { 72 var w bytes.Buffer 73 enc := NewJSONEncoder(&w) 74 if err := enc.Encode(tc.obj); err != nil { 75 t.Fatal(err) 76 } 77 assert.JSONEq(t, tc.expJSON, w.String(), 78 "failed to marshal MoRef to JSON") 79 }) 80 }) 81 } 82 } 83 84 func TestVirtualMachineAffinityInfo(t *testing.T) { 85 // See https://github.com/vmware/govmomi/issues/1008 86 in := VirtualMachineAffinityInfo{ 87 AffinitySet: []int32{0, 1, 2, 3}, 88 } 89 90 b, err := xml.Marshal(in) 91 if err != nil { 92 t.Fatal(err) 93 } 94 95 var out VirtualMachineAffinityInfo 96 97 err = xml.Unmarshal(b, &out) 98 if err != nil { 99 t.Fatal(err) 100 } 101 102 if !reflect.DeepEqual(in, out) { 103 t.Errorf("%#v vs %#v", in, out) 104 } 105 }