From a9f43a12b4c7d50156742859c0b4db3918786d42 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:37:19 +0000 Subject: [PATCH] Integration tier: a preflight for the test member, and setup batches that clean up after a partial failure A member with an admin role and no project membership made the tier fail in every suite with errors about fixtures and empty reads, and one setup batch that partly succeeded left a fixture behind. The preflight checks once that the member can see the system project and create and delete a Story there, and stops with one message saying what it needs. sendFixtures removes what a partly failed setup batch created before it throws. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- AGENTS.md | 9 ++- test/integration/batch.test.ts | 10 ++-- test/integration/guard.test.ts | 6 +- test/integration/instance.ts | 93 ++++++++---------------------- test/integration/instanceConfig.ts | 71 +++++++++++++++++++++++ test/integration/memberCheck.ts | 39 +++++++++++++ test/integration/preflight.ts | 14 +++++ test/integration/resolve.test.ts | 6 +- test/integration/schema.test.ts | 6 +- test/integration/search.test.ts | 8 +-- test/unit/preflight.test.ts | 44 ++++++++++++++ vitest.config.ts | 2 + 12 files changed, 220 insertions(+), 88 deletions(-) create mode 100644 test/integration/instanceConfig.ts create mode 100644 test/integration/memberCheck.ts create mode 100644 test/integration/preflight.ts create mode 100644 test/unit/preflight.test.ts diff --git a/AGENTS.md b/AGENTS.md index 21a661f..56cf833 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -88,8 +88,13 @@ change, by design: `layers.test.ts` (imports point down the layer table), instance, or a hosted instance set aside for API testing and named in `SDK_TEST_ALLOWED_INSTANCES`. Fixtures are named `sdk-integration …` and deleted by exact OID by the test that made them, with `deleteFixtures` - (test/integration/instance.ts), which fails the suite if one is left. - Every query is paged. + (test/integration/instance.ts), which fails the suite if one is left; + a setup batch is sent with `sendFixtures`, which removes what a partly + failed batch created. Every query is paged. The member the tier runs as + (in CI, the one behind the `SDK_TEST_ACCESS_TOKEN` secret) must belong + to the system project (`Scope:0`) with a role that can create and delete + work items; an admin role alone is not enough. A preflight + (test/integration/preflight.ts) says so in one message when it does not. - **Nothing private in the tree.** See `CONTRIBUTING.md`. A URL in an example uses `agility.example.com`. - **A failure never reads as an empty result**, and no read is unbounded diff --git a/test/integration/batch.test.ts b/test/integration/batch.test.ts index 7d563b8..d2fa5ca 100644 --- a/test/integration/batch.test.ts +++ b/test/integration/batch.test.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; import { assetApi } from "../../src/wire"; -import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance"; +import { deleteFixtures, describeInstance, fixtureName, instance, sendFixtures } from "./instance"; /** * batch against a real instance, round trip: a batch that updates two @@ -19,10 +19,10 @@ describeInstance("batch (live)", () => { beforeAll(async () => { me = (await assetApi.query(t, { from: "Member", select: ["Name"], where: { IsSelf: "true" }, page: { size: 1, start: 0 } }))[0]!._oid; - const res = await assetApi.send(t, [ + const res = await sendFixtures(t, [ { AssetType: "Story", Name: fixtureName("batch a"), Scope: { _oid: "Scope:0" }, Estimate: 1 }, { AssetType: "Story", Name: fixtureName("batch b"), Scope: { _oid: "Scope:0" } } - ], { throwOnFailure: true }); + ]); [a, b] = res.assetsCreated.oidTokens.map(assetApi.momentless) as [string, string]; created.push(a, b); }); @@ -110,10 +110,10 @@ describeInstance("batch (live)", () => { const res = await assetApi.send(t, [{ AssetType: "Story", Name: fixtureName(`cascade ${op}`), Scope: { _oid: "Scope:0" } }], { throwOnFailure: true }); const story = assetApi.momentless(res.assetsCreated.oidTokens[0]!); created.push(story); - const tasks = await assetApi.send(t, [ + const tasks = await sendFixtures(t, [ { AssetType: "Task", Name: fixtureName("cascade open"), Parent: { _oid: story } }, { AssetType: "Task", Name: fixtureName("cascade closed before"), Parent: { _oid: story } } - ], { throwOnFailure: true }); + ]); const [open, closedBefore] = tasks.assetsCreated.oidTokens.map(assetApi.momentless) as [string, string]; created.push(open, closedBefore); await assetApi.send(t, [{ from: closedBefore, execute: "QuickClose" }], { throwOnFailure: true }); diff --git a/test/integration/guard.test.ts b/test/integration/guard.test.ts index 7dfdd52..790f27f 100644 --- a/test/integration/guard.test.ts +++ b/test/integration/guard.test.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, expect, it } from "vitest"; import { ConflictError, sendGuarded } from "../../src/services/guard"; import { assetApi } from "../../src/wire"; -import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance"; +import { deleteFixtures, describeInstance, fixtureName, instance, sendFixtures } from "./instance"; /** * The guard against a real instance. Brings its own Stories (deleted @@ -18,10 +18,10 @@ describeInstance("guard (live)", () => { const estimate = async (oid: string) => (await assetApi.query<{ _oid: string; Estimate: string }>(t, { from: oid, select: ["Estimate"], page: { size: 1, start: 0 } }))[0]!.Estimate; beforeAll(async () => { - const res = await assetApi.send(t, [ + const res = await sendFixtures(t, [ { AssetType: "Story", Name: fixtureName("guard a"), Scope: { _oid: "Scope:0" }, Estimate: 1 }, { AssetType: "Story", Name: fixtureName("guard b"), Scope: { _oid: "Scope:0" }, Estimate: 1 } - ], { throwOnFailure: true }); + ]); [a, b] = res.assetsCreated.oidTokens.map(assetApi.momentless) as [string, string]; created.push(a, b); }); diff --git a/test/integration/instance.ts b/test/integration/instance.ts index 5ec5c45..ca5c560 100644 --- a/test/integration/instance.ts +++ b/test/integration/instance.ts @@ -1,76 +1,17 @@ /** - * The dev instance the integration tier runs against. - * - * Resolution, in order: SDK_TEST_URL + SDK_TEST_AUTHORIZATION (a ready - * Authorization header value) or SDK_TEST_ACCESS_TOKEN; else V1_URL + - * V1_ACCESS_TOKEN (the names the CLI consumer and the cloud environment - * use); else the profile named by SDK_TEST_INSTANCE (default "local") in - * ~/.v1config/v1api/config.json, the file the CLI consumer and the - * product's dev tooling share. The credential is read in-process and - * handed to the transport; it is never logged. No instance configured: - * every integration suite skips with a message. - * - * The integration tier writes fixtures, so where it may run is a list, not - * a guess: a local dev instance, or a hosted instance set aside for API - * testing and named in SDK_TEST_ALLOWED_INSTANCES (comma-separated base - * URLs). Any other hosted URL (v1host.com), and anything named - * V1Production, is refused. The list is not committed: a hosted instance's - * URL is the instance's name, and this repository is public. Whoever runs - * the tier against a hosted instance sets the variable beside the - * credential (a local profile needs nothing). + * What the integration suites share: `describe` wrappers that skip with a + * reason when no instance is configured, fixture names, and the creation + * and removal of fixtures. Which instance, and where the tier may run, is + * decided in instanceConfig.ts (kept free of the test runner, so the + * preflight can use it too). */ -import { readFileSync } from "node:fs"; -import { homedir } from "node:os"; -import { join } from "node:path"; import { describe } from "vitest"; -import { createFetchTransport } from "../../src/core/fetchTransport"; import type { Transport } from "../../src/core/transport"; -import { send } from "../../src/wire/assetApi"; -import { apiTestInstances, isHosted, permitted, trim } from "./instanceGuard"; +import { CommandFailureError, momentless, send, type AssetApiResponse } from "../../src/wire/assetApi"; +import type { Command } from "../../src/types/command"; +import { instance, type Instance } from "./instanceConfig"; -export interface Instance { - name: string; - url: string; - transport: Transport; - /** "hosted" for an allowed API-testing instance on v1host.com: shared, so no suite may recycle its app domain. */ - kind: "local" | "hosted"; -} - -function fromProfile(): Instance | null { - const name = process.env.SDK_TEST_INSTANCE ?? "local"; - const file = process.env.V1_CONFIG_FILE ?? join(homedir(), ".v1config", "v1api", "config.json"); - let all: Record; - try { all = JSON.parse(readFileSync(file, "utf8")); } catch { return null; } - const p = all[name]; - if (!p?.v1Url) return null; - const authorization = p.v1AccessToken ? `Bearer ${p.v1AccessToken}` : p.v1Username && p.v1Password ? `Basic ${Buffer.from(`${p.v1Username}:${p.v1Password}`).toString("base64")}` : null; - if (!authorization) return null; - return make(name, p.v1Url, authorization); -} - -function fromEnv(): Instance | null { - const sdk = process.env.SDK_TEST_URL; - if (sdk) { - const authorization = process.env.SDK_TEST_AUTHORIZATION ?? (process.env.SDK_TEST_ACCESS_TOKEN ? `Bearer ${process.env.SDK_TEST_ACCESS_TOKEN}` : undefined); - if (authorization) return make("env", sdk, authorization); - } - const v1 = process.env.V1_URL; - if (v1 && process.env.V1_ACCESS_TOKEN) return make("V1_URL", v1, `Bearer ${process.env.V1_ACCESS_TOKEN}`); - return null; -} - -function make(name: string, url: string, authorization: string): Instance { - return { name, url: trim(url), kind: isHosted(url) ? "hosted" : "local", transport: createFetchTransport({ baseUrl: url, authorization }) }; -} - -export const instance: Instance | null = (() => { - const i = fromEnv() ?? fromProfile(); - if (!i) return null; - if (!permitted(i.url, apiTestInstances())) { - throw new Error(`integration tests write fixtures and must not run against ${i.url}; use a local dev instance, or a hosted instance set aside for API testing and named in SDK_TEST_ALLOWED_INSTANCES`); - } - return i; -})(); +export { instance, type Instance }; /** describe() that runs only when an instance is configured, and says why when it is not. */ export const describeInstance: typeof describe = ((name: string, fn: () => void) => @@ -105,3 +46,19 @@ export async function deleteFixtures(transport: Transport, oids: readonly string } if (left.length) throw new Error(`fixtures left behind:\n${left.join("\n")}`); } + +/** + * Creates a suite's fixtures in one batch. A batch can partly succeed (the + * server applies the commands it accepts and reports the rest), and a + * setup that threw on the failures used to leave what was created with + * nobody holding its OID. This removes whatever was created before it + * throws, so a failed setup leaves nothing behind. + */ +export async function sendFixtures(transport: Transport, commands: Command[]): Promise { + const response = await send(transport, commands); + if (!response.commandFailures?.count) return response; + const made = (response.assetsCreated?.oidTokens ?? []).map(momentless); + // Newest first: what was created later may point at what was created earlier. + await deleteFixtures(transport, [...made].reverse()).catch((error: unknown) => { throw new Error(`a fixture batch partly failed AND its cleanup failed: ${error instanceof Error ? error.message : String(error)}`, { cause: new CommandFailureError(response) }); }); + throw new CommandFailureError(response); +} diff --git a/test/integration/instanceConfig.ts b/test/integration/instanceConfig.ts new file mode 100644 index 0000000..76de47a --- /dev/null +++ b/test/integration/instanceConfig.ts @@ -0,0 +1,71 @@ +/** + * The dev instance the integration tier runs against. + * + * Resolution, in order: SDK_TEST_URL + SDK_TEST_AUTHORIZATION (a ready + * Authorization header value) or SDK_TEST_ACCESS_TOKEN; else V1_URL + + * V1_ACCESS_TOKEN (the names the CLI consumer and the cloud environment + * use); else the profile named by SDK_TEST_INSTANCE (default "local") in + * ~/.v1config/v1api/config.json, the file the CLI consumer and the + * product's dev tooling share. The credential is read in-process and + * handed to the transport; it is never logged. No instance configured: + * every integration suite skips with a message. + * + * The integration tier writes fixtures, so where it may run is a list, not + * a guess: a local dev instance, or a hosted instance set aside for API + * testing and named in SDK_TEST_ALLOWED_INSTANCES (comma-separated base + * URLs). Any other hosted URL (v1host.com), and anything named + * V1Production, is refused. The list is not committed: a hosted instance's + * URL is the instance's name, and this repository is public. Whoever runs + * the tier against a hosted instance sets the variable beside the + * credential (a local profile needs nothing). + */ +import { readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { createFetchTransport } from "../../src/core/fetchTransport"; +import type { Transport } from "../../src/core/transport"; +import { apiTestInstances, isHosted, permitted, trim } from "./instanceGuard"; + +export interface Instance { + name: string; + url: string; + transport: Transport; + /** "hosted" for an allowed API-testing instance on v1host.com: shared, so no suite may recycle its app domain. */ + kind: "local" | "hosted"; +} + +function fromProfile(): Instance | null { + const name = process.env.SDK_TEST_INSTANCE ?? "local"; + const file = process.env.V1_CONFIG_FILE ?? join(homedir(), ".v1config", "v1api", "config.json"); + let all: Record; + try { all = JSON.parse(readFileSync(file, "utf8")); } catch { return null; } + const p = all[name]; + if (!p?.v1Url) return null; + const authorization = p.v1AccessToken ? `Bearer ${p.v1AccessToken}` : p.v1Username && p.v1Password ? `Basic ${Buffer.from(`${p.v1Username}:${p.v1Password}`).toString("base64")}` : null; + if (!authorization) return null; + return make(name, p.v1Url, authorization); +} + +function fromEnv(): Instance | null { + const sdk = process.env.SDK_TEST_URL; + if (sdk) { + const authorization = process.env.SDK_TEST_AUTHORIZATION ?? (process.env.SDK_TEST_ACCESS_TOKEN ? `Bearer ${process.env.SDK_TEST_ACCESS_TOKEN}` : undefined); + if (authorization) return make("env", sdk, authorization); + } + const v1 = process.env.V1_URL; + if (v1 && process.env.V1_ACCESS_TOKEN) return make("V1_URL", v1, `Bearer ${process.env.V1_ACCESS_TOKEN}`); + return null; +} + +function make(name: string, url: string, authorization: string): Instance { + return { name, url: trim(url), kind: isHosted(url) ? "hosted" : "local", transport: createFetchTransport({ baseUrl: url, authorization }) }; +} + +export const instance: Instance | null = (() => { + const i = fromEnv() ?? fromProfile(); + if (!i) return null; + if (!permitted(i.url, apiTestInstances())) { + throw new Error(`integration tests write fixtures and must not run against ${i.url}; use a local dev instance, or a hosted instance set aside for API testing and named in SDK_TEST_ALLOWED_INSTANCES`); + } + return i; +})(); diff --git a/test/integration/memberCheck.ts b/test/integration/memberCheck.ts new file mode 100644 index 0000000..f9b364c --- /dev/null +++ b/test/integration/memberCheck.ts @@ -0,0 +1,39 @@ +/** + * The check the integration tier's preflight runs (preflight.ts), kept + * apart from the instance configuration so it can be unit-tested against + * a fake transport. + * + * Run once before the integration tier: can the configured member do what + * every suite is about to do? If not, the tier stops here with one message + * that says what is missing, where it would otherwise fail in every suite + * with errors about fixtures, empty reads and missing rows that name the + * symptom and not the cause. + * + * What the tier needs of its member: to see the system project (Scope:0) + * and to create and delete a Story in it. A new member with an admin role + * and no project membership has neither: its creates are refused with + * "Invalid Story.Scope" and its reads of work items answer no rows. + */ +import type { Transport } from "../../src/core/transport"; +import { momentless, query, send } from "../../src/wire/assetApi"; + +const PROJECT = "Scope:0"; +const NEEDS = `The member the tier runs as must belong to the system project (${PROJECT}) with a role that can create and delete work items (the tier creates Stories, Defects, Issues and Tasks there, and deletes them).`; + +/** What is wrong with this member for running the tier, as one message; null when nothing is. */ +export async function problemWith(transport: Transport): Promise { + const page = { size: 1, start: 0 }; + const [me] = await query<{ _oid: string; Name: string }>(transport, { from: "Member", select: ["Name"], where: { IsSelf: "true" }, page }); + const who = me ? `${me.Name} (${me._oid})` : "the configured member"; + const [project] = await query(transport, { from: PROJECT, select: ["Name"], page }); + if (!project) return `The integration tier cannot run as ${who}: it cannot see the system project (${PROJECT}). ${NEEDS}`; + const made = await send(transport, [{ AssetType: "Story", Name: `sdk-integration preflight ${new Date().toISOString().replace(/[:.]/g, "-")}`, Scope: PROJECT }]); + const story = made.assetsCreated?.oidTokens?.[0]; + if (!story) { + const said = (made.commandFailures?.commands ?? []).map((c) => (typeof c.error === "string" ? c.error : c.error?.message)).filter(Boolean).join("; "); + return `The integration tier cannot run as ${who}: it cannot create a Story in the system project (${PROJECT})${said ? `; the server answered "${said}"` : ""}. ${NEEDS}`; + } + const removed = await send(transport, [{ from: momentless(story), execute: "Delete" }]); + if (removed.commandFailures?.count) return `The integration tier cannot run as ${who}: it created ${momentless(story)} and cannot delete it, so every fixture would be left behind. Delete that Story by hand. ${NEEDS}`; + return null; +} diff --git a/test/integration/preflight.ts b/test/integration/preflight.ts new file mode 100644 index 0000000..cee7dc1 --- /dev/null +++ b/test/integration/preflight.ts @@ -0,0 +1,14 @@ +/** + * vitest's globalSetup for the integration tier: before any suite, check + * that the configured member can do what the suites need (memberCheck.ts), + * and stop with that one message if it cannot. No instance configured: + * nothing to check, and the suites skip themselves. + */ +import { instance } from "./instanceConfig"; +import { problemWith } from "./memberCheck"; + +export default async function preflight(): Promise { + if (!instance) return; + const problem = await problemWith(instance.transport); + if (problem) throw new Error(problem); +} diff --git a/test/integration/resolve.test.ts b/test/integration/resolve.test.ts index e56df20..ca8a830 100644 --- a/test/integration/resolve.test.ts +++ b/test/integration/resolve.test.ts @@ -1,7 +1,7 @@ import { afterAll, beforeAll, expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; import { assetApi } from "../../src/wire"; -import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance"; +import { deleteFixtures, describeInstance, fixtureName, instance, sendFixtures } from "./instance"; /** * resolve against a real instance. Brings its own data: a Story (resolved @@ -15,12 +15,12 @@ describeInstance("resolve (live)", () => { let story = { oid: "", number: "" }, issue = { oid: "", number: "" }; beforeAll(async () => { - const res = await assetApi.send(t, [ + const res = await sendFixtures(t, [ { "@s": { AssetType: "Story", Name: fixtureName("resolve story"), Scope: { _oid: "Scope:0" } } }, { "@i": { AssetType: "Issue", Name: fixtureName("resolve issue"), Scope: { _oid: "Scope:0" } } }, { from: "@s", select: ["Number"] }, { from: "@i", select: ["Number"] } - ], { throwOnFailure: true }); + ]); created.push(...res.assetsCreated.oidTokens.map(assetApi.momentless)); const [srows, irows] = res.queryResult.results as unknown as { _oid: string; Number: string }[][]; const s = srows![0], i = irows![0]; diff --git a/test/integration/schema.test.ts b/test/integration/schema.test.ts index f5687b8..b818333 100644 --- a/test/integration/schema.test.ts +++ b/test/integration/schema.test.ts @@ -3,7 +3,7 @@ import { AgilityApiClient } from "../../src/client"; import { Schema } from "../../src/services/schema"; import type { Story } from "../../src/types/assets/Story"; import { assetApi } from "../../src/wire"; -import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance"; +import { deleteFixtures, describeInstance, fixtureName, instance, sendFixtures } from "./instance"; /** * The schema service and schema-driven translation against a real @@ -20,11 +20,11 @@ describeInstance("schema (live)", () => { beforeAll(async () => { const [me] = await assetApi.query(t, { from: "Member", select: ["Name"], where: { IsSelf: "true" }, page: { size: 1, start: 0 } }); - const res = await assetApi.send(t, [ + const res = await sendFixtures(t, [ { "@status": { AssetType: "StoryStatus", Name: fixtureName("status"), RollupState: "Active" } }, { "@story": { AssetType: "Story", Name: fixtureName("schema story"), Scope: { _oid: "Scope:0" }, Estimate: 3, Status: "@status", Owners: [{ _oid: me!._oid }] } }, { "@task": { AssetType: "Task", Name: fixtureName("schema task"), Parent: "@story" } } - ], { throwOnFailure: true }); + ]); created.push(...res.assetsCreated.oidTokens.map(assetApi.momentless)); story = created.find((oid) => oid.startsWith("Story:"))!; }); diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts index 31d5ede..70c1574 100644 --- a/test/integration/search.test.ts +++ b/test/integration/search.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; import { CONCRETE_SUBTYPES } from "../../src/types/assets/subtypes"; import { queryV1, rest1 } from "../../src/wire"; -import { deleteFixtures, describeInstance, instance } from "./instance"; +import { deleteFixtures, describeInstance, instance, sendFixtures } from "./instance"; /** * Text search against a real instance: `find` and `findin` on an ordinary @@ -26,13 +26,13 @@ describeInstance("search (live)", () => { (await client.query<{ _oid: string }>({ from: "Workitem", select: ["Name"], findin: ["Name"], sort: ["ID"], page, ...q })).map((r) => r._oid); beforeAll(async () => { - const made = await client.send([ + const made = await sendFixtures(t, [ { AssetType: "Story", Name: `sdk-integration ${word} warehouse shipping`, Description: `described as ${word}desc`, Scope: "Scope:0" }, { AssetType: "Defect", Name: `sdk-integration ${word} accounting`, Scope: "Scope:0" }, { AssetType: "Issue", Name: `sdk-integration ${word} blocker`, Scope: "Scope:0" }, { AssetType: "Story", Name: `sdk-integration ${word} deleted`, Scope: "Scope:0" } - ], { throwOnFailure: true }); - [story, defect, issue, gone] = made.created as [string, string, string, string]; + ]); + [story, defect, issue, gone] = made.assetsCreated.oidTokens.map((oid) => oid.split(":").slice(0, 2).join(":")) as [string, string, string, string]; created.push(story, defect, issue, gone); await client.send([{ from: gone, execute: "Delete" }, { from: defect, execute: "QuickClose" }], { throwOnFailure: true }); storyNumber = String((await client.get(story, ["Number"]))!.Number); diff --git a/test/unit/preflight.test.ts b/test/unit/preflight.test.ts new file mode 100644 index 0000000..7dcdec0 --- /dev/null +++ b/test/unit/preflight.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import type { RequestOptions, Transport } from "../../src/core/transport"; +import { problemWith } from "../integration/memberCheck"; + +/** + * The integration tier's preflight, against a fake transport: it says what + * the member lacks in one message, and leaves nothing behind when all is + * well. The refusal is the server's own, from a run by a member with an + * admin role and no project membership. + */ +const envelope = (over: Record) => ({ requestId: "r", assetsCreated: { oidTokens: [], count: 0 }, assetsModified: { oidTokens: [], count: 0 }, assetsOperatedOn: { oidTokens: [], count: 0 }, commandFailures: { commands: [], count: 0 }, queryResult: { results: [], count: -1 }, ...over }); +function instanceWhere(rule: { seesProject: boolean; creates: boolean; deletes?: boolean }): Transport & { writes: unknown[] } { + const writes: unknown[] = []; + return { + writes, + request: (async (o: RequestOptions) => { + const [command] = o.body as Record[]; + if (command!.from === "Member") return envelope({ queryResult: { results: [[{ _oid: "Member:20", Name: "CI Member" }]], count: 1 } }); + if (command!.from === "Scope:0") return envelope({ queryResult: { results: [rule.seesProject ? [{ _oid: "Scope:0", Name: "System (All Projects)" }] : []], count: 1 } }); + writes.push(command); + if (command!.AssetType === "Story") return rule.creates ? envelope({ assetsCreated: { oidTokens: ["Story:900:1"], count: 1 } }) : envelope({ commandFailures: { count: 1, commands: [{ ...command, error: { message: "Violation'Invalid'Story.Scope", sourceCommandIndex: 0 } }] } }); + return rule.deletes === false ? envelope({ commandFailures: { count: 1, commands: [{ ...command, error: { message: "Security'Delete'Story", sourceCommandIndex: 0 } }] } }) : envelope({ assetsOperatedOn: { oidTokens: ["Story:900:2"], count: 1 } }); + }) as Transport["request"] + }; +} + +describe("the integration tier's preflight", () => { + it("a member that can see the project and create and delete a Story has no problem, and its probe Story is deleted by exact OID", async () => { + const t = instanceWhere({ seesProject: true, creates: true }); + expect(await problemWith(t)).toBeNull(); + expect(t.writes).toEqual([expect.objectContaining({ AssetType: "Story", Scope: "Scope:0", Name: expect.stringMatching(/^sdk-integration preflight /) }), { from: "Story:900", execute: "Delete" }]); + }); + + it("a member with no project membership gets one message: who, what it cannot do, the server's words, and what it needs", async () => { + const unseen = await problemWith(instanceWhere({ seesProject: false, creates: false })); + expect(unseen).toMatch(/cannot run as CI Member \(Member:20\): it cannot see the system project \(Scope:0\)\. The member the tier runs as must belong to the system project/); + const refused = await problemWith(instanceWhere({ seesProject: true, creates: false })); + expect(refused).toMatch(/cannot create a Story in the system project \(Scope:0\); the server answered "Violation'Invalid'Story\.Scope"\. The member .* role that can create and delete work items/); + }); + + it("a member that can create and not delete is told so, with the Story it left, before any suite adds more", async () => { + expect(await problemWith(instanceWhere({ seesProject: true, creates: true, deletes: false }))).toMatch(/created Story:900 and cannot delete it/); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index 1123c63..b8a5095 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -10,6 +10,8 @@ export default defineConfig({ test: { environment: "node", include: integration ? ["test/integration/**/*.test.ts"] : ["test/unit/**/*.test.ts"], + // Before the live tier: one check that its member can do what the suites need, with one clear message if not. + globalSetup: integration ? ["test/integration/preflight.ts"] : [], testTimeout: integration ? 30_000 : 5_000, // One live suite at a time: the custom-fields suite recycles the app // domain, which would fail any other suite talking to the instance.