| 1 |
// Copyright 2026 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package test |
| 15 |
|
| 16 |
import ( |
| 17 |
"fmt" |
| 18 |
"net/url" |
| 19 |
"os" |
| 20 |
"path/filepath" |
| 21 |
"strings" |
| 22 |
"sync" |
| 23 |
"testing" |
| 24 |
"time" |
| 25 |
|
| 26 |
"github.com/nats-io/nats.go" |
| 27 |
testservice "github.com/synadia-io/orbit.go/ntf-client" |
| 28 |
) |
| 29 |
|
| 30 |
// testerProbe caches a one-time reachability check of the tester service so |
| 31 |
// that when it is down, every test fails fast with one actionable message |
| 32 |
// instead of its own raw dial error. |
| 33 |
var testerProbe struct { |
| 34 |
once sync.Once |
| 35 |
err error |
| 36 |
} |
| 37 |
|
| 38 |
// testerURL is set by TestMain: TESTER_NATS_URL when set, otherwise the |
| 39 |
// in-process tester it started. |
| 40 |
var testerURL string |
| 41 |
|
| 42 |
// newTester returns a tester Client connected to the tester service. Close is |
| 43 |
// registered with t.Cleanup. |
| 44 |
func newTester(t testing.TB) *testservice.Client { |
| 45 |
t.Helper() |
| 46 |
testerProbe.once.Do(func() { |
| 47 |
nc, err := nats.Connect(testerURL) |
| 48 |
if err != nil { |
| 49 |
testerProbe.err = fmt.Errorf("cannot reach the tester at %s (unset TESTER_NATS_URL to use the in-process one, or start it with 'make tester-up-host'): %w", testerURL, err) |
| 50 |
return |
| 51 |
} |
| 52 |
fmt.Fprintf(os.Stderr, "tester at %s: nats-server %s\n", testerURL, nc.ConnectedServerVersion()) |
| 53 |
nc.Close() |
| 54 |
}) |
| 55 |
if testerProbe.err != nil { |
| 56 |
t.Fatal(testerProbe.err) |
| 57 |
} |
| 58 |
c := testservice.New(t, testerURL) |
| 59 |
t.Cleanup(func() { c.Close(t) }) |
| 60 |
return c |
| 61 |
} |
| 62 |
|
| 63 |
// testerHost returns the hostname clients use to reach the tester (and the |
| 64 |
// servers it spawns). This is "localhost" for the host-side dev workflow and |
| 65 |
// the in-process tester, and the tester's docker service name (e.g. "nats") |
| 66 |
// in CI. |
| 67 |
func testerHost(t *testing.T) string { |
| 68 |
t.Helper() |
| 69 |
u, err := url.Parse(testerURL) |
| 70 |
if err != nil { |
| 71 |
t.Fatalf("could not parse tester URL %q: %v", testerURL, err) |
| 72 |
} |
| 73 |
return u.Hostname() |
| 74 |
} |
| 75 |
|
| 76 |
// withServer creates a non-JetStream server and dials it. Cleanup via t.Cleanup. |
| 77 |
func withServer(t *testing.T, fn func(*testing.T, *nats.Conn), opts ...testservice.CreateOption) { |
| 78 |
t.Helper() |
| 79 |
withServerInstance(t, func(t *testing.T, nc *nats.Conn, _ *testservice.Instance) { |
| 80 |
fn(t, nc) |
| 81 |
}, opts...) |
| 82 |
} |
| 83 |
|
| 84 |
// withServerInstance is withServer plus the *testservice.Instance so tests can |
| 85 |
// stop/start the server, inspect ports, or open additional connections. |
| 86 |
func withServerInstance(t *testing.T, fn func(*testing.T, *nats.Conn, *testservice.Instance), opts ...testservice.CreateOption) { |
| 87 |
t.Helper() |
| 88 |
c := newTester(t) |
| 89 |
inst := c.CreateServer(t, false, opts...) |
| 90 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 91 |
|
| 92 |
nc := dialInstance(t, inst) |
| 93 |
fn(t, nc, inst) |
| 94 |
} |
| 95 |
|
| 96 |
// withJSServer creates a JetStream-enabled server, dials it, and waits for |
| 97 |
// JetStream to be ready. The callback receives the connection; tests in the |
| 98 |
// `test` package use the legacy nc.JetStream() API to obtain a context. |
| 99 |
// Cleanup via t.Cleanup. |
| 100 |
func withJSServer(t *testing.T, fn func(*testing.T, *nats.Conn), opts ...testservice.CreateOption) { |
| 101 |
t.Helper() |
| 102 |
withJSServerInstance(t, func(t *testing.T, nc *nats.Conn, _ *testservice.Instance) { |
| 103 |
fn(t, nc) |
| 104 |
}, opts...) |
| 105 |
} |
| 106 |
|
| 107 |
// withJSServerInstance is withJSServer plus the *testservice.Instance. |
| 108 |
func withJSServerInstance(t *testing.T, fn func(*testing.T, *nats.Conn, *testservice.Instance), opts ...testservice.CreateOption) { |
| 109 |
t.Helper() |
| 110 |
c := newTester(t) |
| 111 |
inst := c.CreateServer(t, true, opts...) |
| 112 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 113 |
|
| 114 |
nc := dialInstance(t, inst) |
| 115 |
c.WaitForJetStream(t, nc) |
| 116 |
fn(t, nc, inst) |
| 117 |
} |
| 118 |
|
| 119 |
// waitForJSCluster blocks until the meta leader is elected. WaitForJetStream |
| 120 |
// only checks the transport error, so a leaderless cluster answering |
| 121 |
// JSClusterNotAvail satisfies it; AccountInfo parses the response body. |
| 122 |
func waitForJSCluster(t *testing.T, nc *nats.Conn) { |
| 123 |
t.Helper() |
| 124 |
js, err := nc.JetStream() |
| 125 |
if err != nil { |
| 126 |
t.Fatalf("nc.JetStream: %v", err) |
| 127 |
} |
| 128 |
deadline := time.Now().Add(10 * time.Second) |
| 129 |
for { |
| 130 |
_, err := js.AccountInfo() |
| 131 |
if err == nil { |
| 132 |
return |
| 133 |
} |
| 134 |
if time.Now().After(deadline) { |
| 135 |
t.Fatalf("jetstream cluster not ready: %v", err) |
| 136 |
} |
| 137 |
time.Sleep(100 * time.Millisecond) |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
// dialInstance returns a connection that lists every server URL in inst, so |
| 142 |
// reconnect survives any single node going down. nats.MaxReconnects(-1) is |
| 143 |
// always set; additional connect options (e.g. credentials) may be passed. |
| 144 |
// Tests that need custom dial behavior call CreateServer/CreateCluster |
| 145 |
// themselves and then dialInstance directly. Accepts testing.TB so benchmarks |
| 146 |
// can share the helper. |
| 147 |
func dialInstance(t testing.TB, inst *testservice.Instance, opts ...nats.Option) *nats.Conn { |
| 148 |
t.Helper() |
| 149 |
urls := make([]string, len(inst.Servers)) |
| 150 |
for i, s := range inst.Servers { |
| 151 |
urls[i] = s.URL |
| 152 |
} |
| 153 |
connectOpts := append([]nats.Option{nats.MaxReconnects(-1)}, opts...) |
| 154 |
nc, err := nats.Connect(strings.Join(urls, ","), connectOpts...) |
| 155 |
if err != nil { |
| 156 |
t.Fatalf("nats.Connect: %v", err) |
| 157 |
} |
| 158 |
t.Cleanup(nc.Close) |
| 159 |
return nc |
| 160 |
} |
| 161 |
|
| 162 |
// managedTLSOpts wraps WithGeneratedTLS so the generated server cert covers |
| 163 |
// the host clients actually dial — testerHost(t) — in addition to the upstream |
| 164 |
// defaults (localhost, 127.0.0.1, ::1). Locally testerHost is "localhost" |
| 165 |
// (already covered); in sibling-container / CI it's the docker service name |
| 166 |
// ("nats"), which the default cert does not include and would fail x509 |
| 167 |
// verification on. Pass additional TLSOpts (TLSServerOnly, TLSHandshakeFirst, |
| 168 |
// etc.) through varargs. |
| 169 |
func managedTLSOpts(t *testing.T, opts ...testservice.TLSOpt) testservice.CreateOption { |
| 170 |
t.Helper() |
| 171 |
sans := []string{"localhost", "127.0.0.1", "::1"} |
| 172 |
if h := testerHost(t); h != "" && h != "localhost" { |
| 173 |
sans = append(sans, h) |
| 174 |
} |
| 175 |
return testservice.WithGeneratedTLS(append([]testservice.TLSOpt{testservice.TLSSANs(sans...)}, opts...)...) |
| 176 |
} |
| 177 |
|
| 178 |
// tlsCertFiles materializes the managed TLS material on inst to files under |
| 179 |
// t.TempDir() and returns their paths. caPath is always set; clientCertPath |
| 180 |
// and clientKeyPath are "" when the instance is not mutual TLS. Use this when |
| 181 |
// the test exercises file-based nats client options (RootCAs, ClientCert, |
| 182 |
// UserCredentials chained-files, etc.) — pure in-memory uses can call |
| 183 |
// testservice.TLSConfig(inst) directly instead. |
| 184 |
func tlsCertFiles(t *testing.T, inst *testservice.Instance) (caPath, clientCertPath, clientKeyPath string) { |
| 185 |
t.Helper() |
| 186 |
if inst == nil || inst.TLS == nil { |
| 187 |
t.Fatal("instance has no managed TLS material; was WithGeneratedTLS set?") |
| 188 |
} |
| 189 |
dir := t.TempDir() |
| 190 |
caPath = filepath.Join(dir, "ca.pem") |
| 191 |
if err := os.WriteFile(caPath, []byte(inst.TLS.CAPEM), 0o600); err != nil { |
| 192 |
t.Fatalf("could not write CA pem: %v", err) |
| 193 |
} |
| 194 |
if inst.TLS.ClientCertPEM != "" { |
| 195 |
clientCertPath = filepath.Join(dir, "client-cert.pem") |
| 196 |
clientKeyPath = filepath.Join(dir, "client-key.pem") |
| 197 |
if err := os.WriteFile(clientCertPath, []byte(inst.TLS.ClientCertPEM), 0o600); err != nil { |
| 198 |
t.Fatalf("could not write client cert: %v", err) |
| 199 |
} |
| 200 |
if err := os.WriteFile(clientKeyPath, []byte(inst.TLS.ClientKeyPEM), 0o600); err != nil { |
| 201 |
t.Fatalf("could not write client key: %v", err) |
| 202 |
} |
| 203 |
} |
| 204 |
return |
| 205 |
} |
| 206 |
|
| 207 |
// withServerB is the benchmark-flavored variant of withServer. Benchmarks use |
| 208 |
// *testing.B so the with*-style wrappers (whose callbacks take *testing.T) |
| 209 |
// don't fit; this helper inlines the same shape against testing.TB. |
| 210 |
func withServerB(b *testing.B, fn func(*testing.B, *nats.Conn), opts ...testservice.CreateOption) { |
| 211 |
b.Helper() |
| 212 |
c := newTester(b) |
| 213 |
inst := c.CreateServer(b, false, opts...) |
| 214 |
b.Cleanup(func() { inst.Destroy(b) }) |
| 215 |
nc := dialInstance(b, inst) |
| 216 |
fn(b, nc) |
| 217 |
} |