Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions test/integration/batch.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
});
Expand Down Expand Up @@ -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 });
Expand Down
6 changes: 3 additions & 3 deletions test/integration/guard.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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);
});
Expand Down
93 changes: 25 additions & 68 deletions test/integration/instance.ts
Original file line number Diff line number Diff line change
@@ -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<string, { v1Url?: string; v1AccessToken?: string; v1Username?: string; v1Password?: string }>;
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) =>
Expand Down Expand Up @@ -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<AssetApiResponse> {
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);
}
71 changes: 71 additions & 0 deletions test/integration/instanceConfig.ts
Original file line number Diff line number Diff line change
@@ -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<string, { v1Url?: string; v1AccessToken?: string; v1Username?: string; v1Password?: string }>;
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;
})();
39 changes: 39 additions & 0 deletions test/integration/memberCheck.ts
Original file line number Diff line number Diff line change
@@ -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<string | null> {
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;
}
14 changes: 14 additions & 0 deletions test/integration/preflight.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
if (!instance) return;
const problem = await problemWith(instance.transport);
if (problem) throw new Error(problem);
}
6 changes: 3 additions & 3 deletions test/integration/resolve.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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];
Expand Down
6 changes: 3 additions & 3 deletions test/integration/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:"))!;
});
Expand Down
Loading