hashicorp/consul
sdk — test helpers
The github.com/hashicorp/consul/sdk module is the public test toolkit. It is small and focused: anything an external Go application or another HashiCorp project might need to integration-test against Consul lives here.
Sub-packages
| Path | Purpose |
|---|---|
sdk/freeport/ |
Race-free TCP/UDP port allocator. Used everywhere across the repo. |
sdk/iptables/ |
Helpers to set up Connect transparent proxy iptables rules; used by consul connect redirect-traffic and consul-k8s |
sdk/testutil/ |
Build a TestServer that boots a single-node Consul agent for tests; supports config callbacks, snapshots, and TLS |
sdk/testutil/retry/ |
Retry helpers (Run, RunWith(retryer)) used to handle inherently flaky cluster timing |
TestServer
sdk/testutil.TestServer is the workhorse. Most external test suites and HashiCorp's own projects (consul-k8s, consul-template, terraform-provider-consul) start a real consul binary in dev mode under control.
Typical use:
func TestSomething(t *testing.T) {
srv, err := testutil.NewTestServerConfigT(t, func(c *testutil.TestServerConfig) {
c.Bootstrap = true
c.LogLevel = "warn"
})
require.NoError(t, err)
defer srv.Stop()
client, err := api.NewClient(&api.Config{Address: srv.HTTPAddr})
// ... exercise ...
}TestServer uses freeport to pick non-clashing ports, writes a temp config file, execs consul agent -dev, and waits until HTTP is reachable.
freeport
The naive "ask the OS for port 0" pattern leaks ports to other tests in the same process. freeport maintains a process-wide pool of pre-bound ports so concurrent tests don't collide. Implementation: sdk/freeport/freeport.go.
ports := freeport.MustTake(3)
defer freeport.Return(ports)iptables
sdk/iptables/ builds the rule set that redirects all outbound traffic from a pod/container to a sidecar Envoy. It's used by:
consul connect redirect-traffic(command/connect/redirecttraffic/)- consul-k8s (the Kubernetes integration repo)
- consul-dataplane init containers
The package exposes a Setup(cfg Config) function that emits iptables commands with the right chains and rules. It does not run them itself (callers exec with elevated privileges as needed).
Module independence
The sdk has minimal dependencies (no consul agent code). It's safe to import from any test, regardless of whether the parent project pins a specific Consul version.
Entry points for modification
- Add a TestServer config knob: extend
sdk/testutil/server.go::TestServerConfig. - Adjust freeport ranges or behavior:
sdk/freeport/freeport.go. - New iptables rule shape:
sdk/iptables/iptables.go.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.