github.com/vmware/govmomi@v0.37.2/vim25/client_test.go (about)

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