orcid-mock-testing 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Regents of the University of California
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # orcid-mock-testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for [orcid-mock](https://github.com/nemarOrg/orcid-mock), an ephemeral mock of the Open Researcher and Contributor ID (ORCID) service:
4
+ a typed client for its admin API, a Testcontainers module, and Playwright fixtures.
5
+ The [main README](https://github.com/nemarOrg/orcid-mock#test-helpers) has the guide, copy-pasteable examples, and the rules for `ORCID_MOCK_URL` and `ORCID_MOCK_IMAGE`.
6
+
7
+ ## Install
8
+
9
+ The package ships compiled JavaScript (ES modules) with declarations, so it loads under Node 22 or later and under Bun 1.4 or later.
10
+ Both peer dependencies are optional, and each is needed only by the entry point that uses it.
11
+
12
+ ```bash
13
+ bun add -d orcid-mock-testing
14
+ bun add -d testcontainers # ./testcontainers, and the Playwright fixture's containers
15
+ bun add -d @playwright/test # ./playwright
16
+ ```
17
+
18
+ ## Entry points
19
+
20
+ | Import | Provides |
21
+ |---|---|
22
+ | `orcid-mock-testing/client` | `OrcidMockClient(baseUrl)`: `health`, `reset`, `users`, `user`, `createUser`, `putUser`, `deleteUser`, `putClient`, `advanceClock`, `publicBaseUrl`, and `signIn`, the headless sign-in that returns the token response; it ignores proxy variables |
23
+ | `orcid-mock-testing/testcontainers` | `OrcidMockContainer` (`withUsers`, `withImage`, `start()` returning a container with `baseUrl` and a ready `client`), `OrcidMockStartError`, and `startOrConnect()`, which uses `ORCID_MOCK_URL` when it is set and starts a container otherwise |
24
+ | `orcid-mock-testing/playwright` | the `test` and `expect` of a fixture set for `@playwright/test` (`orcidMock`, `signInAs`), and `signInAs(page, iD, { baseUrl })` for any Playwright `Page` |
25
+
26
+ The default image is `ghcr.io/nemarorg/orcid-mock:<this package's version>`, because the helpers are released in lockstep with the server.
@@ -0,0 +1,135 @@
1
+ /** The users-file visibility levels. */
2
+ export type Visibility = "public" | "limited" | "private";
3
+ /**
4
+ * A user in the users-file form (`fixtures/users.schema.json`).
5
+ *
6
+ * Only the fields a helper needs are typed; every record section (`emails`, `works`, and the
7
+ * rest) passes through as `unknown`, and the server validates the whole body. The server package
8
+ * does not export its fixture types, so this is a minimal copy, and `tests/types.ts` fails the
9
+ * type check if the server's `FixtureUser` stops being assignable to it.
10
+ */
11
+ export interface OrcidMockUser {
12
+ /** Empty or absent: the server mints a checksum-valid iD. */
13
+ orcid?: string;
14
+ claimed?: boolean;
15
+ locked?: boolean;
16
+ deactivated?: boolean;
17
+ deprecated_to?: string;
18
+ name: {
19
+ given_names: string;
20
+ family_name?: string | null | undefined;
21
+ credit_name?: string | null | undefined;
22
+ visibility: Visibility;
23
+ };
24
+ [section: string]: unknown;
25
+ }
26
+ /** A user as the admin API returns it: the iD is always filled in. */
27
+ export type OrcidMockUserRecord = OrcidMockUser & {
28
+ orcid: string;
29
+ };
30
+ /** An OAuth client in the users-file form. */
31
+ export interface OrcidMockClientRegistration {
32
+ /** Optional in the body of `putClient`, where the path already names it. */
33
+ client_id?: string;
34
+ client_secret: string;
35
+ name?: string;
36
+ redirect_uris: string[];
37
+ /** A member client may ask for `/read-limited`. */
38
+ member?: boolean;
39
+ }
40
+ /** The answer of `health()` and `reset()`. */
41
+ export interface OrcidMockHealth {
42
+ status: "ok";
43
+ users: number;
44
+ clients: number;
45
+ }
46
+ /** The body of a successful token response; `name` is absent for client credentials. */
47
+ export interface OrcidMockTokenResponse {
48
+ access_token: string;
49
+ token_type: string;
50
+ refresh_token: string;
51
+ expires_in: number;
52
+ scope: string;
53
+ name?: string;
54
+ orcid: string | null;
55
+ id_token?: string;
56
+ }
57
+ export interface SignInOptions {
58
+ /** The iD to sign in as (`login_as`). */
59
+ orcid: string;
60
+ /** Default `/authenticate`. */
61
+ scope?: string;
62
+ /** Default: the starter users file's public client. */
63
+ clientId?: string;
64
+ /** Default: the starter users file's secret. */
65
+ clientSecret?: string;
66
+ /** Must be registered for the client. Default: the starter client's `http://localhost:3000/callback`. */
67
+ redirectUri?: string;
68
+ /** Sent as the OpenID Connect `nonce`. */
69
+ nonce?: string;
70
+ }
71
+ /** The starter users file's public client, which `signIn` uses unless told otherwise. */
72
+ export declare const STARTER_CLIENT_ID = "APP-ORCIDMOCK000001";
73
+ export declare const STARTER_CLIENT_SECRET = "orcid-mock-secret";
74
+ export declare const STARTER_REDIRECT_URI = "http://localhost:3000/callback";
75
+ export interface OrcidMockClientOptions {
76
+ /** Per-request timeout. Default 30 seconds. */
77
+ timeoutMs?: number;
78
+ }
79
+ /** A request the mock refused, or an answer the helper could not use. */
80
+ export declare class OrcidMockError extends Error {
81
+ /** The HTTP status, or 0 when the answer was not an HTTP error (a redirect with no code). */
82
+ readonly status: number;
83
+ /** The response body text, empty when there was none. */
84
+ readonly body: string;
85
+ readonly name = "OrcidMockError";
86
+ constructor(message: string,
87
+ /** The HTTP status, or 0 when the answer was not an HTTP error (a redirect with no code). */
88
+ status: number,
89
+ /** The response body text, empty when there was none. */
90
+ body: string);
91
+ }
92
+ /**
93
+ * Drives one orcid-mock over HTTP. `baseUrl` is the address the test reaches it at, and for a
94
+ * container the same as its `PUBLIC_BASE_URL`.
95
+ */
96
+ export declare class OrcidMockClient {
97
+ #private;
98
+ readonly baseUrl: string;
99
+ constructor(baseUrl: string, options?: OrcidMockClientOptions);
100
+ /** `GET /__admin/health`. */
101
+ health(): Promise<OrcidMockHealth>;
102
+ /**
103
+ * `POST /__admin/reset`: users, clients, counters, and the clock return to the loaded file, and
104
+ * codes, tokens, and sessions are cleared.
105
+ */
106
+ reset(): Promise<OrcidMockHealth>;
107
+ /** `GET /__admin/users`: every user, with minted iDs and put-codes filled in. */
108
+ users(): Promise<OrcidMockUserRecord[]>;
109
+ /** `GET /__admin/users/{iD}`; an unknown iD throws an `OrcidMockError` with status 404. */
110
+ user(orcid: string): Promise<OrcidMockUserRecord>;
111
+ /** `POST /__admin/users`: create only; an omitted `orcid` mints one, an existing iD is a 409. */
112
+ createUser(user: OrcidMockUser): Promise<OrcidMockUserRecord>;
113
+ /** `PUT /__admin/users/{iD}`: create or replace; the path iD wins. */
114
+ putUser(orcid: string, user: OrcidMockUser): Promise<OrcidMockUserRecord>;
115
+ /** `DELETE /__admin/users/{iD}`; an unknown iD throws an `OrcidMockError` with status 404. */
116
+ deleteUser(orcid: string): Promise<void>;
117
+ /** `PUT /__admin/clients/{client_id}`: register or replace an OAuth client. */
118
+ putClient(clientId: string, client: OrcidMockClientRegistration): Promise<OrcidMockClientRegistration>;
119
+ /**
120
+ * `POST /__admin/clock`: moves the server's clock forward so codes, sessions, and tokens expire
121
+ * without sleeping. Returns the new total offset in milliseconds; `reset()` zeroes it.
122
+ */
123
+ advanceClock(seconds: number): Promise<number>;
124
+ /**
125
+ * The address the mock puts in every URL it emits (its `PUBLIC_BASE_URL`), read from the
126
+ * `issuer` of its discovery document. It is `baseUrl` for a container the helper started, and
127
+ * can differ for a running instance, which a browser is then sent to by this address.
128
+ */
129
+ publicBaseUrl(): Promise<string>;
130
+ /**
131
+ * The headless sign-in: `GET /oauth/authorize` with `login_as`, read the code from the
132
+ * `Location` header without following the redirect, then `POST /oauth/token` form-encoded.
133
+ */
134
+ signIn(options: SignInOptions): Promise<OrcidMockTokenResponse>;
135
+ }
package/dist/client.js ADDED
@@ -0,0 +1,171 @@
1
+ import { Agent as HttpAgent, request as httpRequest } from "node:http";
2
+ import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
3
+ /** The starter users file's public client, which `signIn` uses unless told otherwise. */
4
+ export const STARTER_CLIENT_ID = "APP-ORCIDMOCK000001";
5
+ export const STARTER_CLIENT_SECRET = "orcid-mock-secret";
6
+ export const STARTER_REDIRECT_URI = "http://localhost:3000/callback";
7
+ // The client's own agents, never `http.globalAgent`, so a proxy configured on the global agent
8
+ // (NODE_USE_ENV_PROXY) does not apply. No keep-alive: a test's requests are few, and an open
9
+ // socket must not keep a test process alive.
10
+ const HTTP_AGENT = new HttpAgent({ keepAlive: false });
11
+ const HTTPS_AGENT = new HttpsAgent({ keepAlive: false });
12
+ /** A request the mock refused, or an answer the helper could not use. */
13
+ export class OrcidMockError extends Error {
14
+ status;
15
+ body;
16
+ name = "OrcidMockError";
17
+ constructor(message,
18
+ /** The HTTP status, or 0 when the answer was not an HTTP error (a redirect with no code). */
19
+ status,
20
+ /** The response body text, empty when there was none. */
21
+ body) {
22
+ super(message);
23
+ this.status = status;
24
+ this.body = body;
25
+ }
26
+ }
27
+ /**
28
+ * Drives one orcid-mock over HTTP. `baseUrl` is the address the test reaches it at, and for a
29
+ * container the same as its `PUBLIC_BASE_URL`.
30
+ */
31
+ export class OrcidMockClient {
32
+ baseUrl;
33
+ #timeoutMs;
34
+ constructor(baseUrl, options = {}) {
35
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
36
+ this.#timeoutMs = options.timeoutMs ?? 30_000;
37
+ }
38
+ /** `GET /__admin/health`. */
39
+ health() {
40
+ return this.#json("GET", "/__admin/health");
41
+ }
42
+ /**
43
+ * `POST /__admin/reset`: users, clients, counters, and the clock return to the loaded file, and
44
+ * codes, tokens, and sessions are cleared.
45
+ */
46
+ reset() {
47
+ return this.#json("POST", "/__admin/reset");
48
+ }
49
+ /** `GET /__admin/users`: every user, with minted iDs and put-codes filled in. */
50
+ users() {
51
+ return this.#json("GET", "/__admin/users");
52
+ }
53
+ /** `GET /__admin/users/{iD}`; an unknown iD throws an `OrcidMockError` with status 404. */
54
+ user(orcid) {
55
+ return this.#json("GET", `/__admin/users/${encodeURIComponent(orcid)}`);
56
+ }
57
+ /** `POST /__admin/users`: create only; an omitted `orcid` mints one, an existing iD is a 409. */
58
+ createUser(user) {
59
+ return this.#json("POST", "/__admin/users", user);
60
+ }
61
+ /** `PUT /__admin/users/{iD}`: create or replace; the path iD wins. */
62
+ putUser(orcid, user) {
63
+ return this.#json("PUT", `/__admin/users/${encodeURIComponent(orcid)}`, user);
64
+ }
65
+ /** `DELETE /__admin/users/{iD}`; an unknown iD throws an `OrcidMockError` with status 404. */
66
+ async deleteUser(orcid) {
67
+ await this.#request("DELETE", `/__admin/users/${encodeURIComponent(orcid)}`);
68
+ }
69
+ /** `PUT /__admin/clients/{client_id}`: register or replace an OAuth client. */
70
+ putClient(clientId, client) {
71
+ return this.#json("PUT", `/__admin/clients/${encodeURIComponent(clientId)}`, client);
72
+ }
73
+ /**
74
+ * `POST /__admin/clock`: moves the server's clock forward so codes, sessions, and tokens expire
75
+ * without sleeping. Returns the new total offset in milliseconds; `reset()` zeroes it.
76
+ */
77
+ async advanceClock(seconds) {
78
+ const body = await this.#json("POST", "/__admin/clock", {
79
+ advance_seconds: seconds,
80
+ });
81
+ return body.offset_ms;
82
+ }
83
+ /**
84
+ * The address the mock puts in every URL it emits (its `PUBLIC_BASE_URL`), read from the
85
+ * `issuer` of its discovery document. It is `baseUrl` for a container the helper started, and
86
+ * can differ for a running instance, which a browser is then sent to by this address.
87
+ */
88
+ async publicBaseUrl() {
89
+ const discovery = await this.#json("GET", "/.well-known/openid-configuration");
90
+ return discovery.issuer.replace(/\/+$/, "");
91
+ }
92
+ /**
93
+ * The headless sign-in: `GET /oauth/authorize` with `login_as`, read the code from the
94
+ * `Location` header without following the redirect, then `POST /oauth/token` form-encoded.
95
+ */
96
+ async signIn(options) {
97
+ const clientId = options.clientId ?? STARTER_CLIENT_ID;
98
+ const clientSecret = options.clientSecret ?? STARTER_CLIENT_SECRET;
99
+ const redirectUri = options.redirectUri ?? STARTER_REDIRECT_URI;
100
+ const query = new URLSearchParams({
101
+ client_id: clientId,
102
+ response_type: "code",
103
+ scope: options.scope ?? "/authenticate",
104
+ redirect_uri: redirectUri,
105
+ login_as: options.orcid,
106
+ });
107
+ if (options.nonce !== undefined)
108
+ query.set("nonce", options.nonce);
109
+ const authorize = await this.#send("GET", `/oauth/authorize?${query}`);
110
+ const location = authorize.headers.location;
111
+ if (authorize.status !== 302 || location === undefined) {
112
+ throw new OrcidMockError(`GET /oauth/authorize answered ${authorize.status}, not a redirect: ${authorize.text}`, authorize.status, authorize.text);
113
+ }
114
+ // A refusal that ORCID sends back to the client carries `error` in the fragment, not a code.
115
+ const code = new URL(location).searchParams.get("code");
116
+ if (code === null) {
117
+ // A redirect is not an HTTP error, so the error carries no status.
118
+ throw new OrcidMockError(`GET /oauth/authorize redirected without a code: ${location}`, 0, "");
119
+ }
120
+ const token = await this.#send("POST", "/oauth/token", new URLSearchParams({
121
+ grant_type: "authorization_code",
122
+ code,
123
+ client_id: clientId,
124
+ client_secret: clientSecret,
125
+ redirect_uri: redirectUri,
126
+ }).toString(), "application/x-www-form-urlencoded");
127
+ if (token.status !== 200) {
128
+ throw new OrcidMockError(`POST /oauth/token answered ${token.status}: ${token.text}`, token.status, token.text);
129
+ }
130
+ return JSON.parse(token.text);
131
+ }
132
+ /** One request, no redirect followed, no proxy consulted. */
133
+ #send(method, path, body, contentType) {
134
+ const url = new URL(`${this.baseUrl}${path}`);
135
+ const secure = url.protocol === "https:";
136
+ const headers = {};
137
+ if (body !== undefined) {
138
+ headers["content-type"] = contentType ?? "application/json";
139
+ headers["content-length"] = Buffer.byteLength(body);
140
+ }
141
+ return new Promise((resolve, reject) => {
142
+ const outgoing = (secure ? httpsRequest : httpRequest)(url, {
143
+ method,
144
+ headers,
145
+ agent: secure ? HTTPS_AGENT : HTTP_AGENT,
146
+ signal: AbortSignal.timeout(this.#timeoutMs),
147
+ }, (incoming) => {
148
+ const chunks = [];
149
+ incoming.on("data", (chunk) => chunks.push(chunk));
150
+ incoming.on("error", reject);
151
+ incoming.on("end", () => resolve({
152
+ status: incoming.statusCode ?? 0,
153
+ headers: incoming.headers,
154
+ text: Buffer.concat(chunks).toString("utf8"),
155
+ }));
156
+ });
157
+ outgoing.on("error", reject);
158
+ outgoing.end(body);
159
+ });
160
+ }
161
+ async #request(method, path, body) {
162
+ const reply = await this.#send(method, path, body === undefined ? undefined : JSON.stringify(body));
163
+ if (reply.status < 200 || reply.status >= 300) {
164
+ throw new OrcidMockError(`${method} ${path} answered ${reply.status}: ${reply.text}`, reply.status, reply.text);
165
+ }
166
+ return reply;
167
+ }
168
+ async #json(method, path, body) {
169
+ return JSON.parse((await this.#request(method, path, body)).text);
170
+ }
171
+ }
@@ -0,0 +1,41 @@
1
+ import { expect, type Page } from "@playwright/test";
2
+ import { type OrcidMock, type StartOrConnectOptions } from "./start.js";
3
+ export type { OrcidMock, StartOrConnectOptions };
4
+ export { expect };
5
+ export interface SignInAsOptions {
6
+ /**
7
+ * Where the sign-in page is expected, as `<baseUrl>/oauth/authorize`: the address the browser
8
+ * reaches the mock at, and the address the mock puts in its own URLs (its `PUBLIC_BASE_URL`),
9
+ * which is where the sign-in form posts. They are the same for a container, and can differ for
10
+ * a running instance, so pass both then. Only the origin and the path are compared.
11
+ */
12
+ baseUrl: string | readonly string[];
13
+ /** How long to wait for the sign-in page and for the mock to answer. Default 30 seconds. */
14
+ timeoutMs?: number;
15
+ }
16
+ /**
17
+ * Waits until `page` is on the mock's sign-in page, then clicks the button of the user with this
18
+ * iD (its accessible name is "Given Family (iD)", matched as a substring). Returns once the mock
19
+ * has answered the click; a refusal (a locked or deactivated user) throws with the mock's answer.
20
+ * The redirect back to the application is left for the test's next assertion to wait for.
21
+ *
22
+ * When the application signs in in a popup, pass the popup, not the opener:
23
+ * `const popup = await page.waitForEvent("popup"); await signInAs(popup, iD, { baseUrl });`
24
+ */
25
+ export declare function signInAs(page: Page, orcid: string, options: SignInAsOptions): Promise<void>;
26
+ type WorkerFixtures = {
27
+ /** Image and users for the container; ignored when `ORCID_MOCK_URL` names a running instance. */
28
+ orcidMockOptions: StartOrConnectOptions;
29
+ /**
30
+ * The mock for this worker: a running instance (`ORCID_MOCK_URL`) or a container it started.
31
+ * Workers do not share a container, but they do share a running instance: in that mode every
32
+ * worker talks to the same mock and its state, so set `workers: 1` (or give each worker its own
33
+ * users, which a running instance cannot do) and call `orcidMock.client.reset()` between tests.
34
+ */
35
+ orcidMock: OrcidMock;
36
+ };
37
+ type TestFixtures = {
38
+ /** `signInAs` bound to this worker's mock. */
39
+ signInAs: (page: Page, orcid: string) => Promise<void>;
40
+ };
41
+ export declare const test: import("playwright/test").TestType<import("playwright/test").PlaywrightTestArgs & import("playwright/test").PlaywrightTestOptions & TestFixtures, import("playwright/test").PlaywrightWorkerArgs & import("playwright/test").PlaywrightWorkerOptions & WorkerFixtures>;
@@ -0,0 +1,57 @@
1
+ // A Playwright fixture set for orcid-mock: `orcidMock` (one mock per worker) and `signInAs`.
2
+ //
3
+ // import { expect, test } from "orcid-mock-testing/playwright";
4
+ // test("signs in", async ({ page, orcidMock, signInAs }) => {
5
+ // const [alder] = await orcidMock.client.users();
6
+ // await page.goto("/login"); // redirects to the mock's sign-in page
7
+ // await signInAs(page, alder.orcid); // clicks that user's button
8
+ // });
9
+ import { test as base, expect } from "@playwright/test";
10
+ import { startOrConnect } from "./start.js";
11
+ export { expect };
12
+ /**
13
+ * Waits until `page` is on the mock's sign-in page, then clicks the button of the user with this
14
+ * iD (its accessible name is "Given Family (iD)", matched as a substring). Returns once the mock
15
+ * has answered the click; a refusal (a locked or deactivated user) throws with the mock's answer.
16
+ * The redirect back to the application is left for the test's next assertion to wait for.
17
+ *
18
+ * When the application signs in in a popup, pass the popup, not the opener:
19
+ * `const popup = await page.waitForEvent("popup"); await signInAs(popup, iD, { baseUrl });`
20
+ */
21
+ export async function signInAs(page, orcid, options) {
22
+ const timeout = options.timeoutMs ?? 30_000;
23
+ const consentPages = [options.baseUrl].flat().map((address) => {
24
+ const base = new URL(address);
25
+ return { origin: base.origin, path: `${base.pathname.replace(/\/+$/, "")}/oauth/authorize` };
26
+ });
27
+ const onConsentPage = (url) => consentPages.some((page) => url.origin === page.origin && url.pathname === page.path);
28
+ await page.waitForURL(onConsentPage, { timeout });
29
+ // Listen before clicking so the answer cannot be missed; Promise.all keeps the loser of a
30
+ // timeout race from becoming an unhandled rejection.
31
+ const [response] = await Promise.all([
32
+ page.waitForResponse((candidate) => candidate.request().method() === "POST" && onConsentPage(new URL(candidate.url())), { timeout }),
33
+ page.getByRole("button", { name: orcid }).click({ timeout }),
34
+ ]);
35
+ if (response.status() >= 400) {
36
+ throw new Error(`orcid-mock refused the sign-in as ${orcid}: ${response.status()} ${await response.text()}`);
37
+ }
38
+ }
39
+ export const test = base.extend({
40
+ orcidMockOptions: [{}, { scope: "worker", option: true }],
41
+ orcidMock: [
42
+ async ({ orcidMockOptions }, use) => {
43
+ const mock = await startOrConnect(orcidMockOptions);
44
+ try {
45
+ await use(mock);
46
+ }
47
+ finally {
48
+ await mock.stop();
49
+ }
50
+ },
51
+ // Pulling an image and starting a container can take longer than a test's default timeout.
52
+ { scope: "worker", timeout: 120_000 },
53
+ ],
54
+ signInAs: async ({ orcidMock }, use) => {
55
+ await use(async (page, orcid) => signInAs(page, orcid, { baseUrl: [orcidMock.baseUrl, await orcidMock.publicBaseUrl()] }));
56
+ },
57
+ });
@@ -0,0 +1,18 @@
1
+ /** The image repository without a tag. */
2
+ export declare const IMAGE_REPOSITORY = "ghcr.io/nemarorg/orcid-mock";
3
+ /** The port the mock listens on inside the container, fixed by the image. */
4
+ export declare const CONTAINER_PORT = 9700;
5
+ /** Where a users file lands inside the container. */
6
+ export declare const CONTAINER_USERS_PATH = "/fixtures/users.json";
7
+ /**
8
+ * The image that matches this package: helpers are released in lockstep with the server, so the
9
+ * helper's own version is the image tag.
10
+ */
11
+ export declare function defaultImage(): string;
12
+ /** An explicit option wins over `ORCID_MOCK_IMAGE`, which wins over the default. */
13
+ export declare function resolveImage(option?: string): string;
14
+ /**
15
+ * The address of a running instance from `ORCID_MOCK_URL` (the GitHub Action sets it), or
16
+ * undefined when the variable is unset or empty.
17
+ */
18
+ export declare function urlFromEnv(): string | undefined;
package/dist/shared.js ADDED
@@ -0,0 +1,31 @@
1
+ // What every helper agrees on: which image to run and when to use a running instance instead.
2
+ // Internal; the package's exports map does not list this file.
3
+ import pkg from "../package.json" with { type: "json" };
4
+ /** The image repository without a tag. */
5
+ export const IMAGE_REPOSITORY = "ghcr.io/nemarorg/orcid-mock";
6
+ /** The port the mock listens on inside the container, fixed by the image. */
7
+ export const CONTAINER_PORT = 9700;
8
+ /** Where a users file lands inside the container. */
9
+ export const CONTAINER_USERS_PATH = "/fixtures/users.json";
10
+ /**
11
+ * The image that matches this package: helpers are released in lockstep with the server, so the
12
+ * helper's own version is the image tag.
13
+ */
14
+ export function defaultImage() {
15
+ return `${IMAGE_REPOSITORY}:${pkg.version}`;
16
+ }
17
+ /** An explicit option wins over `ORCID_MOCK_IMAGE`, which wins over the default. */
18
+ export function resolveImage(option) {
19
+ if (option !== undefined && option !== "")
20
+ return option;
21
+ const fromEnv = process.env.ORCID_MOCK_IMAGE;
22
+ return fromEnv !== undefined && fromEnv !== "" ? fromEnv : defaultImage();
23
+ }
24
+ /**
25
+ * The address of a running instance from `ORCID_MOCK_URL` (the GitHub Action sets it), or
26
+ * undefined when the variable is unset or empty.
27
+ */
28
+ export function urlFromEnv() {
29
+ const url = process.env.ORCID_MOCK_URL;
30
+ return url === undefined || url === "" ? undefined : url;
31
+ }
@@ -0,0 +1,35 @@
1
+ import { OrcidMockClient } from "./client.js";
2
+ /** The mock could not be started or reached; the message says why, and `cause` holds the error. */
3
+ export declare class OrcidMockStartError extends Error {
4
+ readonly name = "OrcidMockStartError";
5
+ }
6
+ /** A users file: the path of one on disk, or the parsed object (`{ clients, users }`). */
7
+ export type UsersInput = string | Record<string, unknown>;
8
+ export interface StartOrConnectOptions {
9
+ /** Image for a container; see `OrcidMockContainer`. Ignored when connecting. */
10
+ image?: string;
11
+ /** Users for a container. Connecting to a running instance cannot apply them, and throws. */
12
+ users?: UsersInput;
13
+ }
14
+ /** A mock the test can use, wherever it runs. */
15
+ export interface OrcidMock {
16
+ readonly baseUrl: string;
17
+ readonly client: OrcidMockClient;
18
+ /** `url` when `ORCID_MOCK_URL` pointed at a running instance, `container` when one was started. */
19
+ readonly mode: "url" | "container";
20
+ /**
21
+ * The address the mock puts in every URL it emits, which is where a browser is sent to sign in:
22
+ * `baseUrl` for a container, and for a running instance whatever `PUBLIC_BASE_URL` it was
23
+ * started with (read from its discovery document), which can differ from `ORCID_MOCK_URL`.
24
+ */
25
+ publicBaseUrl(): Promise<string>;
26
+ /** Stops a container this call started; a running instance is never stopped. */
27
+ stop(): Promise<void>;
28
+ }
29
+ /**
30
+ * Connects to the instance at `ORCID_MOCK_URL` when that variable is set (the GitHub Action sets
31
+ * it), and starts a container otherwise. A running instance's users cannot be changed from here,
32
+ * so a `users` option with `ORCID_MOCK_URL` set is an error: load the users where the instance
33
+ * starts (the Action's `users-file` input).
34
+ */
35
+ export declare function startOrConnect(options?: StartOrConnectOptions): Promise<OrcidMock>;
package/dist/start.js ADDED
@@ -0,0 +1,57 @@
1
+ // `startOrConnect`: use a running orcid-mock when `ORCID_MOCK_URL` names one, and start a
2
+ // container otherwise. It lives apart from `testcontainers.ts` so that a run against a running
3
+ // instance never loads the `testcontainers` package (an optional peer dependency).
4
+ import { OrcidMockClient } from "./client.js";
5
+ import { urlFromEnv } from "./shared.js";
6
+ /** The mock could not be started or reached; the message says why, and `cause` holds the error. */
7
+ export class OrcidMockStartError extends Error {
8
+ name = "OrcidMockStartError";
9
+ }
10
+ /**
11
+ * Connects to the instance at `ORCID_MOCK_URL` when that variable is set (the GitHub Action sets
12
+ * it), and starts a container otherwise. A running instance's users cannot be changed from here,
13
+ * so a `users` option with `ORCID_MOCK_URL` set is an error: load the users where the instance
14
+ * starts (the Action's `users-file` input).
15
+ */
16
+ export async function startOrConnect(options = {}) {
17
+ const url = urlFromEnv();
18
+ if (url !== undefined) {
19
+ if (options.users !== undefined) {
20
+ throw new OrcidMockStartError(`ORCID_MOCK_URL is set (${url}), so a running orcid-mock is used and its users cannot be set here. Load them where it starts, or unset ORCID_MOCK_URL to start a container.`);
21
+ }
22
+ const client = new OrcidMockClient(url);
23
+ try {
24
+ await client.health();
25
+ }
26
+ catch (error) {
27
+ throw new OrcidMockStartError(`ORCID_MOCK_URL is set (${url}) but orcid-mock does not answer there`, {
28
+ cause: error,
29
+ });
30
+ }
31
+ let publicBaseUrl;
32
+ return {
33
+ baseUrl: client.baseUrl,
34
+ client,
35
+ mode: "url",
36
+ publicBaseUrl: () => {
37
+ publicBaseUrl ??= client.publicBaseUrl();
38
+ return publicBaseUrl;
39
+ },
40
+ stop: async () => { },
41
+ };
42
+ }
43
+ const { OrcidMockContainer } = await import("./testcontainers.js");
44
+ const container = new OrcidMockContainer(options.image);
45
+ if (options.users !== undefined)
46
+ container.withUsers(options.users);
47
+ const started = await container.start();
48
+ return {
49
+ baseUrl: started.baseUrl,
50
+ client: started.client,
51
+ mode: "container",
52
+ publicBaseUrl: async () => started.baseUrl,
53
+ stop: async () => {
54
+ await started.stop();
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,45 @@
1
+ import { AbstractStartedContainer, GenericContainer, type StartedTestContainer } from "testcontainers";
2
+ import { OrcidMockClient } from "./client.js";
3
+ import { type UsersInput } from "./start.js";
4
+ export { OrcidMockStartError, type UsersInput } from "./start.js";
5
+ /** An orcid-mock container that has started and answered its readiness line. */
6
+ export declare class StartedOrcidMockContainer extends AbstractStartedContainer {
7
+ /** The address the mock is reachable at from the host, and its `PUBLIC_BASE_URL`. */
8
+ readonly baseUrl: string;
9
+ /** A client for the admin API and the headless sign-in. */
10
+ readonly client: OrcidMockClient;
11
+ constructor(started: StartedTestContainer, baseUrl: string);
12
+ }
13
+ /**
14
+ * ```ts
15
+ * const mock = await new OrcidMockContainer().withUsers("fixtures/users.json").start();
16
+ * const token = await mock.client.signIn({ orcid: "0000-0002-1825-0097" });
17
+ * await mock.stop();
18
+ * ```
19
+ *
20
+ * The image is the constructor argument, else `ORCID_MOCK_IMAGE`, else the image that matches
21
+ * this package's version. The Docker daemon must be on the machine that runs the tests, since the
22
+ * base URL is `http://localhost:<port>`.
23
+ */
24
+ export declare class OrcidMockContainer extends GenericContainer {
25
+ #private;
26
+ constructor(image?: string);
27
+ /** Replaces the image, whatever the constructor chose. */
28
+ withImage(image: string): this;
29
+ /**
30
+ * Serves this users file instead of the bundled starter users. The content is copied into the
31
+ * container with mode 0644, so it works whatever the file's own permissions are (a bind mount
32
+ * must be readable by the image's `nonroot` user) and with a remote Docker daemon.
33
+ * A path is read now, so a missing file throws an `OrcidMockStartError` here, with its path; an
34
+ * object is serialized now. Calling it again replaces the earlier file.
35
+ */
36
+ withUsers(users: UsersInput): this;
37
+ start(): Promise<StartedOrcidMockContainer>;
38
+ /**
39
+ * A host port to publish on. The operating system's answer can be taken by the time Docker binds
40
+ * it, which `start()` survives by asking again; a subclass can answer otherwise to prove that.
41
+ */
42
+ protected pickPort(): Promise<number>;
43
+ protected containerCreated(containerId: string): Promise<void>;
44
+ }
45
+ export { type OrcidMock, type StartOrConnectOptions, startOrConnect } from "./start.js";
@@ -0,0 +1,212 @@
1
+ // A Testcontainers module for orcid-mock. `startOrConnect`, which uses a running instance
2
+ // (`ORCID_MOCK_URL`) when there is one and starts a container otherwise, is re-exported from here.
3
+ //
4
+ // The mock never derives its own address from the request (its `PUBLIC_BASE_URL` fixes the issuer
5
+ // and every URL it emits), so the host port must be chosen before the container starts and the
6
+ // base URL handed to it. The port is bound explicitly, on the loopback interface only: the admin
7
+ // API has no authentication.
8
+ import { readFileSync } from "node:fs";
9
+ import { createServer } from "node:net";
10
+ import { AbstractStartedContainer, GenericContainer, getContainerRuntimeClient, ImageName, Wait, } from "testcontainers";
11
+ import { OrcidMockClient } from "./client.js";
12
+ import { CONTAINER_PORT, CONTAINER_USERS_PATH, resolveImage } from "./shared.js";
13
+ import { OrcidMockStartError } from "./start.js";
14
+ export { OrcidMockStartError } from "./start.js";
15
+ /** Attempts at picking a free port before giving up; a lost race is the only reason to retry. */
16
+ const PORT_ATTEMPTS = 3;
17
+ const READY = /"event":"listening"/;
18
+ const LOG_TAIL_LINES = 100;
19
+ const LOG_TAIL_BYTES = 16 * 1024;
20
+ /** A port the operating system says is free right now. */
21
+ function freePort() {
22
+ return new Promise((resolve, reject) => {
23
+ const server = createServer();
24
+ server.once("error", reject);
25
+ server.listen(0, "127.0.0.1", () => {
26
+ const address = server.address();
27
+ if (address === null || typeof address === "string") {
28
+ server.close();
29
+ reject(new Error("could not read the port the operating system picked"));
30
+ return;
31
+ }
32
+ server.close(() => resolve(address.port));
33
+ });
34
+ });
35
+ }
36
+ function readUsersFile(path) {
37
+ try {
38
+ return readFileSync(path, "utf8");
39
+ }
40
+ catch (error) {
41
+ const reason = error instanceof Error ? error.message : String(error);
42
+ throw new OrcidMockStartError(`cannot read the users file ${path}: ${reason}`, {
43
+ cause: error,
44
+ });
45
+ }
46
+ }
47
+ /** Docker's answer for a container that is already gone. */
48
+ function isNotFound(error) {
49
+ return (typeof error === "object" &&
50
+ error !== null &&
51
+ error.statusCode === 404);
52
+ }
53
+ function isPortConflict(error) {
54
+ const message = error instanceof Error ? error.message : String(error);
55
+ return /port is already allocated|address already in use|ports are not available/i.test(message);
56
+ }
57
+ /** An orcid-mock container that has started and answered its readiness line. */
58
+ export class StartedOrcidMockContainer extends AbstractStartedContainer {
59
+ /** The address the mock is reachable at from the host, and its `PUBLIC_BASE_URL`. */
60
+ baseUrl;
61
+ /** A client for the admin API and the headless sign-in. */
62
+ client;
63
+ constructor(started, baseUrl) {
64
+ super(started);
65
+ this.baseUrl = baseUrl;
66
+ this.client = new OrcidMockClient(baseUrl);
67
+ }
68
+ }
69
+ /**
70
+ * ```ts
71
+ * const mock = await new OrcidMockContainer().withUsers("fixtures/users.json").start();
72
+ * const token = await mock.client.signIn({ orcid: "0000-0002-1825-0097" });
73
+ * await mock.stop();
74
+ * ```
75
+ *
76
+ * The image is the constructor argument, else `ORCID_MOCK_IMAGE`, else the image that matches
77
+ * this package's version. The Docker daemon must be on the machine that runs the tests, since the
78
+ * base URL is `http://localhost:<port>`.
79
+ */
80
+ export class OrcidMockContainer extends GenericContainer {
81
+ #containerId;
82
+ #logTail = "";
83
+ constructor(image) {
84
+ super(resolveImage(image));
85
+ this.withEnvironment({ HOST: "0.0.0.0" })
86
+ .withWaitStrategy(Wait.forLogMessage(READY))
87
+ .withStartupTimeout(60_000)
88
+ // Testcontainers removes a container that never became ready, so keep its output now.
89
+ .withLogConsumer((stream) => {
90
+ stream.on("data", (chunk) => {
91
+ this.#logTail = (this.#logTail + chunk.toString()).slice(-LOG_TAIL_BYTES);
92
+ });
93
+ });
94
+ }
95
+ /** Replaces the image, whatever the constructor chose. */
96
+ withImage(image) {
97
+ this.imageName = ImageName.fromString(image);
98
+ return this;
99
+ }
100
+ /**
101
+ * Serves this users file instead of the bundled starter users. The content is copied into the
102
+ * container with mode 0644, so it works whatever the file's own permissions are (a bind mount
103
+ * must be readable by the image's `nonroot` user) and with a remote Docker daemon.
104
+ * A path is read now, so a missing file throws an `OrcidMockStartError` here, with its path; an
105
+ * object is serialized now. Calling it again replaces the earlier file.
106
+ */
107
+ withUsers(users) {
108
+ const content = typeof users === "string" ? readUsersFile(users) : JSON.stringify(users);
109
+ this.contentsToCopy = this.contentsToCopy.filter((copy) => copy.target !== CONTAINER_USERS_PATH);
110
+ return this.withCopyContentToContainer([
111
+ { content, target: CONTAINER_USERS_PATH, mode: 0o644 },
112
+ ]).withEnvironment({ USERS_FILE: CONTAINER_USERS_PATH });
113
+ }
114
+ async start() {
115
+ for (let attempt = 1;; attempt++) {
116
+ const port = await this.pickPort();
117
+ const baseUrl = `http://localhost:${port}`;
118
+ this.#bind(port, baseUrl);
119
+ this.#containerId = undefined;
120
+ this.#logTail = "";
121
+ try {
122
+ const started = new StartedOrcidMockContainer(await super.start(), baseUrl);
123
+ await waitUntilReachable(started.client);
124
+ return started;
125
+ }
126
+ catch (error) {
127
+ const { logs, problems } = await this.#discard();
128
+ if (attempt < PORT_ATTEMPTS && isPortConflict(error))
129
+ continue;
130
+ throw new OrcidMockStartError(`orcid-mock did not start from ${this.imageName.string}: ${error instanceof Error ? error.message : String(error)}${logs === "" ? "" : `\n--- container output ---\n${logs}`}${problems.length === 0 ? "" : `\n--- cleanup ---\n${problems.join("\n")}`}`, { cause: error });
131
+ }
132
+ }
133
+ }
134
+ /**
135
+ * A host port to publish on. The operating system's answer can be taken by the time Docker binds
136
+ * it, which `start()` survives by asking again; a subclass can answer otherwise to prove that.
137
+ */
138
+ pickPort() {
139
+ return freePort();
140
+ }
141
+ async containerCreated(containerId) {
142
+ this.#containerId = containerId;
143
+ }
144
+ /**
145
+ * After a failed start: the tail of the container's output, which holds the server's own message
146
+ * (a users file it rejected, say), and the container removed. Testcontainers removes a container
147
+ * that never became ready, but leaves one that exited before its ports were bound for its
148
+ * reaper at the end of the process; that one is read and removed here. Touches only the
149
+ * container this start created. Each step that fails is reported in `problems`, so a container
150
+ * that could not be removed is never left silently.
151
+ */
152
+ async #discard() {
153
+ const problems = [];
154
+ if (this.#containerId === undefined)
155
+ return { logs: this.#logTail.trim(), problems };
156
+ let logs = this.#logTail;
157
+ try {
158
+ const client = await getContainerRuntimeClient();
159
+ const container = client.container.getById(this.#containerId);
160
+ if (logs === "") {
161
+ try {
162
+ const stream = await client.container.logs(container, { tail: LOG_TAIL_LINES });
163
+ for await (const chunk of stream)
164
+ logs += chunk.toString();
165
+ }
166
+ catch (error) {
167
+ if (!isNotFound(error))
168
+ problems.push(`could not read the container's output: ${error}`);
169
+ }
170
+ }
171
+ try {
172
+ await container.remove({ force: true, v: true });
173
+ }
174
+ catch (error) {
175
+ // Testcontainers may have removed it already; anything else leaves a container behind.
176
+ if (!isNotFound(error)) {
177
+ problems.push(`could not remove container ${this.#containerId.slice(0, 12)}: ${error}`);
178
+ }
179
+ }
180
+ }
181
+ catch (error) {
182
+ problems.push(`could not reach the container runtime to clean up: ${error}`);
183
+ }
184
+ return { logs: logs.trim(), problems };
185
+ }
186
+ /** Publishes the container port on `port`, loopback only, and tells the mock its address. */
187
+ #bind(port, baseUrl) {
188
+ const key = `${CONTAINER_PORT}/tcp`;
189
+ this.exposedPorts = [{ container: CONTAINER_PORT, host: port }];
190
+ this.createOpts.ExposedPorts = { [key]: {} };
191
+ this.hostConfig.PortBindings = { [key]: [{ HostIp: "127.0.0.1", HostPort: String(port) }] };
192
+ this.withEnvironment({ PUBLIC_BASE_URL: baseUrl });
193
+ }
194
+ }
195
+ /** The readiness line says the server listens; this says the published port reaches it. */
196
+ async function waitUntilReachable(client) {
197
+ let lastError;
198
+ for (let attempt = 0; attempt < 25; attempt++) {
199
+ try {
200
+ await client.health();
201
+ return;
202
+ }
203
+ catch (error) {
204
+ lastError = error;
205
+ await new Promise((resolve) => setTimeout(resolve, 200));
206
+ }
207
+ }
208
+ throw new OrcidMockStartError(`the container is up but ${client.baseUrl} does not answer`, {
209
+ cause: lastError,
210
+ });
211
+ }
212
+ export { startOrConnect } from "./start.js";
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "orcid-mock-testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-rc.1",
4
+ "description": "Test helpers for orcid-mock, an ephemeral mock of the ORCID service: a typed admin client, a Testcontainers module, and a Playwright fixture",
5
+ "license": "MIT",
6
+ "private": false,
7
+ "type": "module",
8
+ "packageManager": "bun@1.4.5",
9
+ "engines": {
10
+ "node": ">=22",
11
+ "bun": ">=1.4"
12
+ },
13
+ "exports": {
14
+ "./client": {
15
+ "types": "./dist/client.d.ts",
16
+ "default": "./dist/client.js"
17
+ },
18
+ "./testcontainers": {
19
+ "types": "./dist/testcontainers.d.ts",
20
+ "default": "./dist/testcontainers.js"
21
+ },
22
+ "./playwright": {
23
+ "types": "./dist/playwright.d.ts",
24
+ "default": "./dist/playwright.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist/",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
34
+ "lint": "biome ci .",
35
+ "format": "biome check --write .",
36
+ "typecheck": "tsc --noEmit -p tsconfig.json",
37
+ "test": "bun test --coverage"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/nemarOrg/orcid-mock",
45
+ "directory": "clients/node"
46
+ },
47
+ "homepage": "https://github.com/nemarOrg/orcid-mock#test-helpers",
48
+ "bugs": {
49
+ "url": "https://github.com/nemarOrg/orcid-mock/issues"
50
+ },
51
+ "keywords": [
52
+ "orcid",
53
+ "mock",
54
+ "testing",
55
+ "testcontainers",
56
+ "playwright",
57
+ "oauth2"
58
+ ],
59
+ "peerDependencies": {
60
+ "@playwright/test": "^1.63.0",
61
+ "testcontainers": "^12.1.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@playwright/test": {
65
+ "optional": true
66
+ },
67
+ "testcontainers": {
68
+ "optional": true
69
+ }
70
+ },
71
+ "devDependencies": {
72
+ "@biomejs/biome": "2.6.8",
73
+ "@playwright/test": "1.65.1",
74
+ "@types/bun": "1.4.5",
75
+ "playwright": "1.65.1",
76
+ "testcontainers": "12.2.2",
77
+ "typescript": "7.0.2"
78
+ }
79
+ }