github.com/juju/juju@v0.0.0-20240327075706-a90865de2538/api/apiclient_whitebox_test.go (about)

     1  // Copyright 2018 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package api
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"net"
    10  	"regexp"
    11  	"time"
    12  
    13  	"github.com/juju/testing"
    14  	jc "github.com/juju/testing/checkers"
    15  	gc "gopkg.in/check.v1"
    16  
    17  	jtesting "github.com/juju/juju/testing"
    18  )
    19  
    20  type apiclientWhiteboxSuite struct {
    21  	testing.IsolationSuite
    22  }
    23  
    24  var _ = gc.Suite(&apiclientWhiteboxSuite{})
    25  
    26  func (s *apiclientWhiteboxSuite) TestDialWebsocketMultiCancelled(c *gc.C) {
    27  	ctx := context.TODO()
    28  	ctx, cancel := context.WithCancel(ctx)
    29  	started := make(chan struct{})
    30  	go func() {
    31  		select {
    32  		case <-started:
    33  		case <-time.After(jtesting.LongWait):
    34  			c.Fatalf("timed out waiting %s for started", jtesting.LongWait)
    35  		}
    36  		<-time.After(10 * time.Millisecond)
    37  		if cancel != nil {
    38  			c.Logf("cancelling")
    39  			cancel()
    40  		}
    41  	}()
    42  	listen, err := net.Listen("tcp4", ":0")
    43  	c.Assert(err, jc.ErrorIsNil)
    44  	addr := listen.Addr().String()
    45  	c.Logf("listening at: %s", addr)
    46  	// Note that we Listen, but we never Accept
    47  	close(started)
    48  	info := &Info{
    49  		Addrs: []string{addr},
    50  	}
    51  	opts := DialOpts{
    52  		DialAddressInterval: 50 * time.Millisecond,
    53  		RetryDelay:          40 * time.Millisecond,
    54  		Timeout:             100 * time.Millisecond,
    55  		DialTimeout:         100 * time.Millisecond,
    56  	}
    57  	// Close before we connect
    58  	listen.Close()
    59  	_, err = dialAPI(ctx, info, opts)
    60  	c.Check(err, gc.ErrorMatches, fmt.Sprintf("dial tcp %s:.*", regexp.QuoteMeta(addr)))
    61  }
    62  
    63  func (s *apiclientWhiteboxSuite) TestDialWebsocketMultiClosed(c *gc.C) {
    64  	listen, err := net.Listen("tcp4", ":0")
    65  	c.Assert(err, jc.ErrorIsNil)
    66  	addr := listen.Addr().String()
    67  	c.Logf("listening at: %s", addr)
    68  	// Note that we Listen, but we never Accept
    69  	info := &Info{
    70  		Addrs: []string{addr},
    71  	}
    72  	opts := DialOpts{
    73  		DialAddressInterval: 1 * time.Second,
    74  		RetryDelay:          1 * time.Second,
    75  		Timeout:             2 * time.Second,
    76  		DialTimeout:         3 * time.Second,
    77  	}
    78  	listen.Close()
    79  	_, _, err = DialAPI(info, opts)
    80  	c.Check(err, gc.ErrorMatches, fmt.Sprintf("unable to connect to API: dial tcp %s:.*", regexp.QuoteMeta(addr)))
    81  }