Skip to content

Commit

Permalink
tests(conn): simplify test connections to enable different transports…
Browse files Browse the repository at this point in the history
… to use the tests

Signed-off-by: Alberto Ricart <alberto@synadia.com>
  • Loading branch information
aricart committed Nov 2, 2024
1 parent c48451e commit 7648c7e
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 45 deletions.
35 changes: 15 additions & 20 deletions core/tests/auth_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,9 @@ const conf = {

Deno.test("auth - none", async () => {
const ns = await NatsServer.start(conf);

await assertRejects(
async () => {
const nc = await connect(
{ port: ns.port },
);
await nc.close();
fail("shouldnt have been able to connect");
() => {
return ns.connect({ reconnect: false });
},
errors.AuthorizationError,
);
Expand All @@ -84,12 +79,8 @@ Deno.test("auth - none", async () => {
Deno.test("auth - bad", async () => {
const ns = await NatsServer.start(conf);
await assertRejects(
async () => {
const nc = await connect(
{ port: ns.port, user: "me", pass: "hello" },
);
await nc.close();
fail("shouldnt have been able to connect");
() => {
return ns.connect({ user: "me", pass: "hello" });
},
errors.AuthorizationError,
);
Expand All @@ -105,18 +96,16 @@ Deno.test("auth - weird chars", async () => {
},
});

const nc = await connect(
{ port: ns.port, user: "admin", pass: pass },
);
const nc = await ns.connect({ user: "admin", pass: pass });
await nc.flush();
await nc.close();
await ns.stop();
});

Deno.test("auth - un/pw", async () => {
const ns = await NatsServer.start(conf);
const nc = await connect(
{ port: ns.port, user: "derek", pass: "foobar" },
const nc = await ns.connect(
{ user: "derek", pass: "foobar" },
);
await nc.flush();
await nc.close();
Expand All @@ -125,9 +114,8 @@ Deno.test("auth - un/pw", async () => {

Deno.test("auth - un/pw authenticator", async () => {
const ns = await NatsServer.start(conf);
const nc = await connect(
const nc = await ns.connect(
{
port: ns.port,
authenticator: usernamePasswordAuthenticator("derek", "foobar"),
},
);
Expand Down Expand Up @@ -1312,3 +1300,10 @@ Deno.test("auth - account expired", async () => {

await cleanup(ns, nc);
});

Deno.test("env conn", async () => {
const ns = await NatsServer.start();
const nc = await ns.connect({ debug: true });
await nc.flush();
await cleanup(ns, nc);
});
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"enable-npm-workspace": "mv _package.json package.json"
},
"fmt": {
"include": ["transport-deno/", "bin/", "core/", "debug/", "jetstream/", "kv/", "obj/", "services/", "*.md", "transport-node/"],
"include": ["transport-deno/", "bin/", "core/", "debug/", "jetstream/", "kv/", "obj/", "services/", "*.md", "transport-node/", "test_helpers/"],
"exclude": ["core/lib", "jetstream/lib", "kv/lib","obj/lib", "services/lib", "transport-node/lib", "transport-ws/lib", "*/build", "docs/"]
},
"lint": {
Expand Down
4 changes: 2 additions & 2 deletions test_helpers/asserts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@
import { assertGreaterOrEqual, assertLessOrEqual } from "jsr:@std/assert";

export function assertBetween(n: number, low: number, high: number) {
assertGreaterOrEqual(n, low, `${n} >= ${low}`)
assertLessOrEqual(n, high, `${n} <= ${high}`)
assertGreaterOrEqual(n, low, `${n} >= ${low}`);
assertLessOrEqual(n, high, `${n} <= ${high}`);
}
37 changes: 32 additions & 5 deletions test_helpers/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,16 @@ import { rgb24 } from "jsr:@std/fmt/colors";
import { check, jsopts } from "./mod.ts";
import { extend, timeout } from "../core/src/util.ts";
import type { Deferred } from "../core/src/util.ts";
import { deferred, delay, nuid } from "../core/src/mod.ts";
import {
ConnectionOptions,
deferred,
delay,
NatsConnection,
nuid,
wsconnect,
} from "../core/src/mod.ts";
import { Certs } from "./certs.ts";
import { connect } from "./connect.ts";

export const ServerSignals = Object.freeze({
QUIT: "SIGQUIT",
Expand Down Expand Up @@ -637,8 +645,14 @@ export class NatsServer implements PortInfo {
conf.leafnodes = conf.leafnodes || {};
conf.leafnodes.listen = conf.leafnodes.listen || "127.0.0.1:-1";
conf.server_tags = Array.isArray(conf.server_targs)
? conf.server_tags.push(`id:${nuid.next()}`)
: [`id:${nuid.next()}`];
? conf.server_tags.push(`id:${nuid.next()}`)
: [`id:${nuid.next()}`];

conf.websocket = Object.assign(
{},
{ port: -1, no_tls: true },
conf.websocket || {},
);

return conf;
}
Expand Down Expand Up @@ -681,9 +695,19 @@ export class NatsServer implements PortInfo {
return tlsconfig;
}

connect(opts: ConnectionOptions = {}): Promise<NatsConnection> {
if (Deno.env.get("websocket")) {
const proto = this.config.websocket.no_tls ? "ws" : "wss";
opts.servers = `${proto}://localhost:${this.websocket}`;
return wsconnect(opts);
}
opts.port = this.port;
return connect(opts);
}

static async start(conf?: any, debug = false): Promise<NatsServer> {
// const exe = Deno.env.get("CI") ? "nats-server/nats-server" : "nats-server";
const exe = "nats-server";
const exe = "nats-server";
const tmp = resolve(Deno.env.get("TMPDIR") || ".");
conf = NatsServer.confDefaults(conf);
conf.ports_file_dir = tmp;
Expand Down Expand Up @@ -813,7 +837,10 @@ export function toConf(o: any, indent?: string): string {
buf.push(`${pad}${k}: ${v}`);
}
} else {
if (v.includes(" ") || v.startsWith("$") || ((v.includes("{{") && v.includes("}")))) {
if (
v.includes(" ") || v.startsWith("$") ||
(v.includes("{{") && v.includes("}"))
) {
buf.push(`${pad}"${v}"`);
} else {
buf.push(pad + v);
Expand Down
30 changes: 13 additions & 17 deletions test_helpers/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ import { ConnectFn } from "../core/src/core.ts";
export { check } from "./check.ts";
export { Lock } from "./lock.ts";
export { Connection, TestServer } from "./test_server.ts";
export {
assertBetween,
} from "./asserts.ts";
export { assertBetween } from "./asserts.ts";
export { NatsServer, ServerSignals } from "./launcher.ts";

export function disabled(reason: string): void {
Expand All @@ -51,12 +49,12 @@ export function jsopts() {
}

export function wsopts() {
return {
websocket: {
no_tls: true,
port: -1,
},
};
return {
websocket: {
no_tls: true,
port: -1,
},
};
}

export function jetstreamExportServerConf(
Expand Down Expand Up @@ -99,21 +97,19 @@ export function jetstreamServerConf(
return conf as Record<string, unknown>;
}

export function wsServerConf(opts: unknown = {}): Record<string,unknown> {
export function wsServerConf(opts: unknown = {}): Record<string, unknown> {
return Object.assign(wsopts(), opts);
}

export async function _setup(
fn: ConnectFn,
_fn: ConnectFn,
serverConf?: Record<string, unknown>,
clientOpts?: Partial<ConnectionOptions>,
): Promise<{ ns: NatsServer; nc: NatsConnection }> {
const dt = serverConf as { debug: boolean; trace: boolean };
const debug = dt && (dt.debug || dt.trace);
const ns = await NatsServer.start(serverConf, debug);
clientOpts = clientOpts ? clientOpts : {};
const copts = extend({ port: ns.port }, clientOpts) as ConnectionOptions;
const nc = await fn(copts);
const nc = await ns.connect(clientOpts);
return { ns, nc };
}

Expand Down Expand Up @@ -156,8 +152,8 @@ export async function notCompatible(
}

export function flakyTest(
fn: () => void | Promise<void>,
{ count = 3 } = {},
fn: () => void | Promise<void>,
{ count = 3 } = {},
): () => Promise<void> {
return async () => {
const errors: Error[] = [];
Expand All @@ -169,5 +165,5 @@ export function flakyTest(
}
}
throw new AggregateError(errors);
}
};
}

0 comments on commit 7648c7e

Please sign in to comment.