github.com/vmware/govmomi@v0.37.2/session/keep_alive_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 session_test
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"sync"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/vmware/govmomi/session"
    27  	"github.com/vmware/govmomi/simulator"
    28  	"github.com/vmware/govmomi/vim25"
    29  	"github.com/vmware/govmomi/vim25/soap"
    30  )
    31  
    32  func TestKeepAlive(t *testing.T) {
    33  	simulator.Test(func(ctx context.Context, c *vim25.Client) {
    34  		m := session.NewManager(c)
    35  
    36  		err := m.Logout(ctx)
    37  		if err != nil {
    38  			t.Fatal(err)
    39  		}
    40  
    41  		var mu sync.Mutex
    42  		n := 0
    43  		c.RoundTripper = vim25.Retry(c.Client, vim25.RetryTemporaryNetworkError, 3)
    44  		c.RoundTripper = session.KeepAliveHandler(c.RoundTripper, time.Millisecond, func(soap.RoundTripper) error {
    45  			mu.Lock()
    46  			n++
    47  			mu.Unlock()
    48  			return errors.New("stop") // stops the keep alive routine
    49  		})
    50  
    51  		err = m.Login(ctx, simulator.DefaultLogin) // starts the keep alive routine
    52  		if err != nil {
    53  			t.Fatal(err)
    54  		}
    55  
    56  		time.Sleep(time.Millisecond * 10)
    57  		mu.Lock()
    58  		if n != 1 {
    59  			t.Errorf("handler called %d times", n)
    60  		}
    61  		mu.Unlock()
    62  	})
    63  }