github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/e2e/e2eutil/consul.go (about)

     1  package e2eutil
     2  
     3  import (
     4  	"time"
     5  
     6  	capi "github.com/hashicorp/consul/api"
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  // RequireConsulStatus asserts the aggregate health of the service converges to
    11  // the expected status
    12  func RequireConsulStatus(require *require.Assertions,
    13  	client *capi.Client, serviceName, expectedStatus string) {
    14  	require.Eventually(func() bool {
    15  		_, status := serviceStatus(require, client, serviceName)
    16  		return status == expectedStatus
    17  	}, 30*time.Second, time.Second, // needs a long time for killing tasks/clients
    18  		"timed out expecting %q to become %q",
    19  		serviceName, expectedStatus,
    20  	)
    21  }
    22  
    23  // serviceStatus gets the aggregate health of the service and returns
    24  // the []ServiceEntry for further checking
    25  func serviceStatus(require *require.Assertions,
    26  	client *capi.Client, serviceName string) ([]*capi.ServiceEntry, string) {
    27  	services, _, err := client.Health().Service(serviceName, "", false, nil)
    28  	require.NoError(err, "expected no error for %q, got %v", serviceName, err)
    29  	if len(services) > 0 {
    30  		return services, services[0].Checks.AggregatedStatus()
    31  	}
    32  	return nil, "(unknown status)"
    33  }
    34  
    35  // RequireConsulDeregistered asserts that the service eventually is deregistered from Consul
    36  func RequireConsulDeregistered(require *require.Assertions,
    37  	client *capi.Client, serviceName string) {
    38  	require.Eventually(func() bool {
    39  		services, _, err := client.Health().Service(serviceName, "", false, nil)
    40  		require.NoError(err, "expected no error for %q, got %v", serviceName, err)
    41  		return len(services) == 0
    42  	}, 5*time.Second, time.Second)
    43  }