github.com/vmware/govmomi@v0.51.0/vim25/types/types_test.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package types 6 7 import ( 8 "bytes" 9 "reflect" 10 "testing" 11 12 "github.com/stretchr/testify/assert" 13 14 "github.com/vmware/govmomi/vim25/xml" 15 ) 16 17 func TestManagedObjectReference(t *testing.T) { 18 19 testCases := []struct { 20 name string 21 obj ManagedObjectReference 22 expXML string 23 expJSON string 24 }{ 25 { 26 name: "with server GUID", 27 obj: ManagedObjectReference{ 28 Type: "fake", 29 Value: "fake", 30 ServerGUID: "fake", 31 }, 32 expXML: `<ManagedObjectReference type="fake" serverGuid="fake">fake</ManagedObjectReference>`, 33 expJSON: `{"_typeName":"ManagedObjectReference","type":"fake","value":"fake","serverGuid":"fake"}`, 34 }, 35 { 36 name: "sans server GUID", 37 obj: ManagedObjectReference{ 38 Type: "fake", 39 Value: "fake", 40 }, 41 expXML: `<ManagedObjectReference type="fake">fake</ManagedObjectReference>`, 42 expJSON: `{"_typeName":"ManagedObjectReference","type":"fake","value":"fake"}`, 43 }, 44 } 45 46 for i := range testCases { 47 tc := testCases[i] // capture the test case 48 49 t.Run(tc.name, func(t *testing.T) { 50 t.Run("xml", func(t *testing.T) { 51 act, err := xml.Marshal(tc.obj) 52 if err != nil { 53 t.Fatal(err) 54 } 55 if e, a := tc.expXML, string(act); e != a { 56 t.Fatalf("failed to marshal MoRef to XML: exp=%s, act=%s", e, a) 57 } 58 }) 59 t.Run("json", func(t *testing.T) { 60 var w bytes.Buffer 61 enc := NewJSONEncoder(&w) 62 if err := enc.Encode(tc.obj); err != nil { 63 t.Fatal(err) 64 } 65 assert.JSONEq(t, tc.expJSON, w.String(), 66 "failed to marshal MoRef to JSON") 67 }) 68 }) 69 } 70 } 71 72 func TestVirtualMachineAffinityInfo(t *testing.T) { 73 // See https://github.com/vmware/govmomi/issues/1008 74 in := VirtualMachineAffinityInfo{ 75 AffinitySet: []int32{0, 1, 2, 3}, 76 } 77 78 b, err := xml.Marshal(in) 79 if err != nil { 80 t.Fatal(err) 81 } 82 83 var out VirtualMachineAffinityInfo 84 85 err = xml.Unmarshal(b, &out) 86 if err != nil { 87 t.Fatal(err) 88 } 89 90 if !reflect.DeepEqual(in, out) { 91 t.Errorf("%#v vs %#v", in, out) 92 } 93 }