• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..27-Sep-2021-

retry/H27-Sep-2021-320237

README.mdH A D27-Sep-20212.1 KiB7960

assertions.goH A D27-Sep-2021484 2014

context.goH A D27-Sep-2021203 1411

io.goH A D27-Sep-20212.3 KiB8354

server.goH A D27-Sep-202116.9 KiB547418

server_methods.goH A D27-Sep-20217 KiB257197

server_wrapper.goH A D27-Sep-20211.6 KiB6642

testlog.goH A D27-Sep-20211.6 KiB6444

types.goH A D27-Sep-2021437 127

README.md

1Consul Testing Utilities
2========================
3
4This package provides some generic helpers to facilitate testing in Consul.
5
6TestServer
7==========
8
9TestServer is a harness for managing Consul agents and initializing them with
10test data. Using it, you can form test clusters, create services, add health
11checks, manipulate the K/V store, etc. This test harness is completely decoupled
12from Consul's core and API client, meaning it can be easily imported and used in
13external unit tests for various applications. It works by invoking the Consul
14CLI, which means it is a requirement to have Consul installed in the `$PATH`.
15
16Following is an example usage:
17
18```go
19package my_program
20
21import (
22	"testing"
23
24	"github.com/hashicorp/consul/consul/structs"
25	"github.com/hashicorp/consul/sdk/testutil"
26)
27
28func TestFoo_bar(t *testing.T) {
29	// Create a test Consul server
30	srv1, err := testutil.NewTestServerConfigT(t, nil)
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.NewTestServerConfigT(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```
79