github.com/Iqoqo/consul@v1.4.5/testutil/README.md (about)

     1  Consul Testing Utilities
     2  ========================
     3  
     4  This package provides some generic helpers to facilitate testing in Consul.
     5  
     6  TestServer
     7  ==========
     8  
     9  TestServer is a harness for managing Consul agents and initializing them with
    10  test data. Using it, you can form test clusters, create services, add health
    11  checks, manipulate the K/V store, etc. This test harness is completely decoupled
    12  from Consul's core and API client, meaning it can be easily imported and used in
    13  external unit tests for various applications. It works by invoking the Consul
    14  CLI, which means it is a requirement to have Consul installed in the `$PATH`.
    15  
    16  Following is an example usage:
    17  
    18  ```go
    19  package my_program
    20  
    21  import (
    22  	"testing"
    23  
    24  	"github.com/hashicorp/consul/consul/structs"
    25  	"github.com/hashicorp/consul/testutil"
    26  )
    27  
    28  func TestFoo_bar(t *testing.T) {
    29  	// Create a test Consul server
    30  	srv1, err := testutil.NewTestServer()
    31  	if err != nil {
    32  		t.Fatal(err)
    33  	}
    34  	defer srv1.Stop()
    35  
    36  	// Create a secondary server, passing in configuration
    37  	// to avoid bootstrapping as we are forming a cluster.
    38  	srv2, err := testutil.NewTestServerConfig(t, func(c *testutil.TestServerConfig) {
    39  		c.Bootstrap = false
    40  	})
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  	defer srv2.Stop()
    45  
    46  	// Join the servers together
    47  	srv1.JoinLAN(t, srv2.LANAddr)
    48  
    49  	// Create a test key/value pair
    50  	srv1.SetKV(t, "foo", []byte("bar"))
    51  
    52  	// Create lots of test key/value pairs
    53  	srv1.PopulateKV(t, map[string][]byte{
    54  		"bar": []byte("123"),
    55  		"baz": []byte("456"),
    56  	})
    57  
    58  	// Create a service
    59  	srv1.AddService(t, "redis", structs.HealthPassing, []string{"master"})
    60  
    61  	// Create a service that will be accessed in target source code
    62  	srv1.AddAccessibleService("redis", structs.HealthPassing, "127.0.0.1", 6379, []string{"master"})
    63  
    64  	// Create a service check
    65  	srv1.AddCheck(t, "service:redis", "redis", structs.HealthPassing)
    66  
    67  	// Create a node check
    68  	srv1.AddCheck(t, "mem", "", structs.HealthCritical)
    69  
    70  	// The HTTPAddr field contains the address of the Consul
    71  	// API on the new test server instance.
    72  	println(srv1.HTTPAddr)
    73  
    74  	// All functions also have a wrapper method to limit the passing of "t"
    75  	wrap := srv1.Wrap(t)
    76  	wrap.SetKV("foo", []byte("bar"))
    77  }
    78  ```