github.com/vmware/govmomi@v0.37.1/test/helper.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 test 18 19 import ( 20 "context" 21 "net/url" 22 "os" 23 "testing" 24 25 "github.com/vmware/govmomi/vim25" 26 "github.com/vmware/govmomi/vim25/methods" 27 "github.com/vmware/govmomi/vim25/soap" 28 "github.com/vmware/govmomi/vim25/types" 29 ) 30 31 // URL parses the GOVMOMI_TEST_URL environment variable if set. 32 func URL() *url.URL { 33 s := os.Getenv("GOVMOMI_TEST_URL") 34 if s == "" { 35 return nil 36 } 37 u, err := soap.ParseURL(s) 38 if err != nil { 39 panic(err) 40 } 41 return u 42 } 43 44 // NewAuthenticatedClient creates a new vim25.Client, authenticates the user 45 // specified in the test URL, and returns it. 46 func NewAuthenticatedClient(t *testing.T) *vim25.Client { 47 u := URL() 48 if u == nil { 49 t.SkipNow() 50 } 51 52 soapClient := soap.NewClient(u, true) 53 vimClient, err := vim25.NewClient(context.Background(), soapClient) 54 if err != nil { 55 t.Fatal(err) 56 } 57 58 req := types.Login{ 59 This: *vimClient.ServiceContent.SessionManager, 60 } 61 62 req.UserName = u.User.Username() 63 if pw, ok := u.User.Password(); ok { 64 req.Password = pw 65 } 66 67 _, err = methods.Login(context.Background(), vimClient, &req) 68 if err != nil { 69 t.Fatal(err) 70 } 71 72 return vimClient 73 }