github.com/vmware/govmomi@v0.51.0/vim25/client_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 vim25 6 7 import ( 8 "context" 9 "encoding/json" 10 "net/url" 11 "os" 12 "testing" 13 14 "github.com/vmware/govmomi/vim25/methods" 15 "github.com/vmware/govmomi/vim25/mo" 16 "github.com/vmware/govmomi/vim25/soap" 17 "github.com/vmware/govmomi/vim25/types" 18 ) 19 20 // Duplicated to prevent cyclic dependency... 21 func testURL(t *testing.T) *url.URL { 22 s := os.Getenv("GOVMOMI_TEST_URL") 23 if s == "" { 24 t.SkipNow() 25 } 26 u, err := soap.ParseURL(s) 27 if err != nil { 28 panic(err) 29 } 30 return u 31 } 32 33 func sessionLogin(t *testing.T, c *Client) { 34 req := types.Login{ 35 This: *c.ServiceContent.SessionManager, 36 } 37 38 u := testURL(t).User 39 req.UserName = u.Username() 40 if pw, ok := u.Password(); ok { 41 req.Password = pw 42 } 43 44 _, err := methods.Login(context.Background(), c, &req) 45 if err != nil { 46 t.Fatal(err) 47 } 48 } 49 50 func sessionCheck(t *testing.T, c *Client) { 51 var mgr mo.SessionManager 52 53 err := mo.RetrieveProperties(context.Background(), c, c.ServiceContent.PropertyCollector, *c.ServiceContent.SessionManager, &mgr) 54 if err != nil { 55 t.Fatal(err) 56 } 57 } 58 59 func TestClientSerialization(t *testing.T) { 60 var c1, c2 *Client 61 62 soapClient := soap.NewClient(testURL(t), true) 63 c1, err := NewClient(context.Background(), soapClient) 64 if err != nil { 65 t.Fatal(err) 66 } 67 68 // Login 69 sessionLogin(t, c1) 70 sessionCheck(t, c1) 71 72 // Serialize/deserialize 73 b, err := json.Marshal(c1) 74 if err != nil { 75 t.Fatal(err) 76 } 77 c2 = &Client{} 78 err = json.Unmarshal(b, c2) 79 if err != nil { 80 t.Fatal(err) 81 } 82 83 // Check the session is still valid 84 sessionCheck(t, c2) 85 }