feat: add issue create and comment (task 0004)
All checks were successful
CI / test (pull_request) Successful in 24s
CI / test (push) Successful in 28s

Introduce the first mutations, along with the shared machinery the later
issue and PR mutation slices reuse.

- `issue create` with --title/--body/--body-file/--assignee/--label/
  --milestone/--fields, emitting `issue: { number, title, state, url }`
- `issue comment <n>`, echoing the created comment from the POST response
  with the body cleaned and truncated at 800 chars
- body-source resolution (--body vs --body-file), label and milestone
  name->ID lookup, repeatable flags, and the `joined`/`selectExtraFields`
  field extractors

Label lookup pages until exhausted, since a repo with more labels than one
page would otherwise fail to resolve a valid name. The end-to-end tier seeds
a mixed-case label and milestone and passes both in a different case, so the
case-insensitive lookup is verified against live Gitea rather than only
against fixtures.
This commit was merged in pull request #3.
This commit is contained in:
2026-07-11 20:39:01 -04:00
parent 5e66b4d746
commit f82414a933
13 changed files with 1328 additions and 41 deletions

121
test/e2e/mutations.test.ts Normal file
View File

@@ -0,0 +1,121 @@
import { beforeAll, describe, expect, it } from "vitest";
import { runCliTest } from "../harness.js";
import {
fetchComments,
fetchIssue,
provisionInstance,
type E2EInstance,
} from "./provision.js";
/**
* The end-to-end tier for the issue mutations. These commands lean on behavior
* the fixture server cannot attest to — above all that Gitea's label and
* milestone name lookups really are case-insensitive, and that `CreateIssueOption`
* really takes label *ids* rather than names. Both are asserted here against a
* live instance by passing names in a different case than they were seeded in.
*/
const E2E_URL = process.env.GITEA_AXI_E2E_URL;
/** Read the `number:` scalar out of a rendered detail block. */
function renderedNumber(stdout: string): number {
const match = stdout.match(/^\s*number:\s*(\d+)$/m);
expect(match, `no number field in output:\n${stdout}`).not.toBeNull();
return Number(match![1]);
}
describe.skipIf(!E2E_URL)("end-to-end: issue mutations", () => {
let instance: E2EInstance;
function env(): Record<string, string> {
return {
GITEA_AXI_API_URL: instance.baseUrl,
GITEA_AXI_TOKEN: instance.token,
GITEA_AXI_REPO: `${instance.owner}/${instance.repo}`,
};
}
beforeAll(async () => {
instance = await provisionInstance(E2E_URL!);
}, 150_000);
it("creates an issue and reports the live number, state, and url", async () => {
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "E2E created issue", "--body", "Created by the e2e tier."],
{ env: env() },
);
expect(exitCode).toBe(0);
expect(stdout).toContain("issue:");
expect(stdout).toContain("title: E2E created issue");
expect(stdout).toContain("state: open");
expect(stdout).toContain(`${instance.owner}/${instance.repo}/issues/`);
const created = await fetchIssue(instance, renderedNumber(stdout));
expect(created.title).toBe("E2E created issue");
expect(created.body).toBe("Created by the e2e tier.");
});
it("resolves a differently-cased --label and --milestone against live Gitea", async () => {
// The seeds are "E2E-Bug" and "E2E-Milestone"; both are passed here in a
// case that does not match, which is the whole point of the assertion.
const { stdout, exitCode } = await runCliTest(
[
"issue",
"create",
"--title",
"E2E labelled issue",
"--label",
instance.labelName.toLowerCase(),
"--milestone",
instance.milestoneTitle.toUpperCase(),
],
{ env: env() },
);
expect(exitCode).toBe(0);
const created = await fetchIssue(instance, renderedNumber(stdout));
const labels = (created.labels ?? []) as { name?: string }[];
expect(labels.map((label) => label.name)).toEqual([instance.labelName]);
const milestone = created.milestone as { title?: string } | null;
expect(milestone?.title).toBe(instance.milestoneTitle);
});
it("rejects an unknown label name without creating the issue", async () => {
const before = await runCliTest(["issue", "list", "--limit", "1"], { env: env() });
const totalBefore = before.stdout.match(/of (\d+) total/)![1];
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "E2E never created", "--label", "no-such-label"],
{ env: env() },
);
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
const after = await runCliTest(["issue", "list", "--limit", "1"], { env: env() });
expect(after.stdout).toContain(`of ${totalBefore} total`);
});
it("posts a comment on a live issue and echoes it back", async () => {
const created = await runCliTest(["issue", "create", "--title", "E2E comment target"], {
env: env(),
});
const number = renderedNumber(created.stdout);
const { stdout, exitCode } = await runCliTest(
["issue", "comment", String(number), "--body", "A comment from the e2e tier."],
{ env: env() },
);
expect(exitCode).toBe(0);
expect(stdout).toContain("comment:");
expect(stdout).toContain(`number: ${number}`);
expect(stdout).toContain(`author: ${instance.owner}`);
expect(stdout).toContain("body: A comment from the e2e tier.");
const comments = await fetchComments(instance, number);
expect(comments).toHaveLength(1);
expect(comments[0]!.body).toBe("A comment from the e2e tier.");
});
});

View File

@@ -22,6 +22,14 @@ export interface E2EInstance {
openTitles: string[];
/** Title of the single seeded closed issue. */
closedTitle: string;
/**
* A label seeded in mixed case. The mutation tier passes it in a *different*
* case, so the case-insensitive name→id lookup is exercised against live Gitea
* rather than only against fixtures.
*/
labelName: string;
/** A milestone seeded in mixed case, for the same reason as {@link labelName}. */
milestoneTitle: string;
}
const USERNAME = "e2e-admin";
@@ -188,7 +196,55 @@ export async function provisionInstance(baseUrl: string): Promise<E2EInstance> {
state: "closed",
});
return { baseUrl: normalized, owner: USERNAME, repo, token, openTitles, closedTitle };
const labelName = "E2E-Bug";
await apiRequest(normalized, "POST", `/repos/${USERNAME}/${repo}/labels`, token, {
name: labelName,
color: "#ff0000",
});
const milestoneTitle = "E2E-Milestone";
await apiRequest(normalized, "POST", `/repos/${USERNAME}/${repo}/milestones`, token, {
title: milestoneTitle,
});
return {
baseUrl: normalized,
owner: USERNAME,
repo,
token,
openTitles,
closedTitle,
labelName,
milestoneTitle,
};
}
/** Fetch a single issue as Gitea returns it, for verifying what a mutation wrote. */
export async function fetchIssue(
instance: E2EInstance,
number: number,
): Promise<Record<string, unknown>> {
const res = await apiRequest(
instance.baseUrl,
"GET",
`/repos/${instance.owner}/${instance.repo}/issues/${number}`,
instance.token,
);
return (await res.json()) as Record<string, unknown>;
}
/** Fetch an issue's comments as Gitea returns them. */
export async function fetchComments(
instance: E2EInstance,
number: number,
): Promise<Record<string, unknown>[]> {
const res = await apiRequest(
instance.baseUrl,
"GET",
`/repos/${instance.owner}/${instance.repo}/issues/${number}/comments`,
instance.token,
);
return (await res.json()) as Record<string, unknown>[];
}
/**

View File

@@ -1,5 +1,5 @@
import { readFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import { createServer, type IncomingMessage, type Server } from "node:http";
export interface FixtureRoute {
method: string;
@@ -20,6 +20,8 @@ export interface RecordedRequest {
path: string;
query: Record<string, string>;
headers: Record<string, string>;
/** Parsed JSON request body; undefined when the request carried none. */
body?: unknown;
}
export interface FixtureServer {
@@ -49,6 +51,26 @@ function matches(route: FixtureRoute, request: RecordedRequest): boolean {
return true;
}
/** Collect the request stream, parsing it as JSON when it carried a payload. */
async function readRequestBody(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of req) {
chunks.push(chunk as Buffer);
}
if (chunks.length === 0) {
return undefined;
}
const raw = Buffer.concat(chunks).toString("utf8");
if (!raw) {
return undefined;
}
try {
return JSON.parse(raw);
} catch {
return raw;
}
}
export async function startFixtureServer(routes: FixtureRoute[]): Promise<FixtureServer> {
const requests: RecordedRequest[] = [];
const server: Server = createServer((req, res) => {
@@ -62,21 +84,24 @@ export async function startFixtureServer(routes: FixtureRoute[]): Promise<Fixtur
),
};
requests.push(recorded);
const route = routes.find((candidate) => matches(candidate, recorded));
if (!route) {
res.writeHead(599, { "content-type": "application/json" });
res.end(
JSON.stringify({
message: `no fixture route matched ${recorded.method} ${recorded.path} ${JSON.stringify(recorded.query)}`,
}),
);
return;
}
res.writeHead(route.status ?? 200, {
"content-type": "application/json",
...route.headers,
void readRequestBody(req).then((body) => {
recorded.body = body;
const route = routes.find((candidate) => matches(candidate, recorded));
if (!route) {
res.writeHead(599, { "content-type": "application/json" });
res.end(
JSON.stringify({
message: `no fixture route matched ${recorded.method} ${recorded.path} ${JSON.stringify(recorded.query)}`,
}),
);
return;
}
res.writeHead(route.status ?? 200, {
"content-type": "application/json",
...route.headers,
});
res.end(JSON.stringify(loadBody(route)));
});
res.end(JSON.stringify(loadBody(route)));
});
await new Promise<void>((resolve) => {
server.listen(0, "127.0.0.1", resolve);

View File

@@ -1,4 +1,9 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect } from "vitest";
import { runCli } from "../src/cli.js";
import type { FixtureServer } from "./fixture-server.js";
export interface CliResult {
stdout: string;
@@ -40,3 +45,40 @@ export function testModeEnv(apiUrl: string): Record<string, string> {
GITEA_AXI_REPO: "testowner/testrepo",
};
}
/**
* Throwaway files for the `--body-file` paths, cleaned up together. Call
* {@link TempFiles.write} to create one and {@link TempFiles.cleanup} from an
* `afterEach`.
*/
export interface TempFiles {
write: (name: string, content: string) => string;
cleanup: () => void;
}
export function tempFiles(): TempFiles {
const dirs: string[] = [];
return {
write: (name, content) => {
const dir = mkdtempSync(join(tmpdir(), "gitea-axi-test-"));
dirs.push(dir);
const path = join(dir, name);
writeFileSync(path, content, "utf8");
return path;
},
cleanup: () => {
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
},
};
}
/** The parsed body of the single POST the CLI sent to `path`; fails if it sent none. */
export function postedBody(server: FixtureServer, path: string): Record<string, unknown> {
const post = server.requests.find(
(request) => request.method === "POST" && request.path === path,
);
expect(post, `expected a POST to ${path}`).toBeDefined();
return post!.body as Record<string, unknown>;
}

190
test/issue-comment.test.ts Normal file
View File

@@ -0,0 +1,190 @@
import { afterEach, describe, expect, it } from "vitest";
import { startFixtureServer, type FixtureServer } from "./fixture-server.js";
import { postedBody, runCliTest, tempFiles, testModeEnv } from "./harness.js";
const COMMENTS_PATH = "/api/v1/repos/testowner/testrepo/issues/42/comments";
let server: FixtureServer;
const files = tempFiles();
afterEach(async () => {
await server.close();
files.cleanup();
});
function createdComment(fields: Record<string, unknown> = {}): Record<string, unknown> {
return {
id: 900,
user: { login: "alexion" },
created_at: "2026-07-01T00:00:00Z",
body: "Looks good to me.",
...fields,
};
}
function postedComment(): Record<string, unknown> {
return postedBody(server, COMMENTS_PATH);
}
describe("issue comment", () => {
it("posts the comment and renders number, author, created, and body", async () => {
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 201, body: createdComment() },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "comment", "42", "--body", "Looks good to me."],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).toContain("comment:");
// `number` is the issue commented on, not the comment's own id.
expect(stdout).toContain("number: 42");
expect(stdout).toContain("author: alexion");
expect(stdout).toContain("body: Looks good to me.");
expect(stdout).not.toContain("900");
expect(postedComment()).toEqual({ body: "Looks good to me." });
});
it("reads the body from --body-file", async () => {
const path = files.write("comment.md", "From a file.");
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 201, body: createdComment() },
]);
const { exitCode } = await runCliTest(
["issue", "comment", "42", "--body-file", path],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedComment()).toEqual({ body: "From a file." });
});
it("truncates a comment body over 800 chars in the output, with the inline hint", async () => {
const body = "z".repeat(1000);
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 201, body: createdComment({ body }) },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "comment", "42", "--body", body],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).toContain(
`... (truncated, ${body.length} chars total - use --full to see complete body)`,
);
// The posted body itself is never truncated — only its echo in the output.
expect(postedComment()).toEqual({ body });
});
it("echoes the untruncated body with --full", async () => {
const body = "z".repeat(1000);
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 201, body: createdComment({ body }) },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "comment", "42", "--body", body, "--full"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).toContain(body);
expect(stdout).not.toContain("truncated");
});
it("cleans a long comment body before truncating it", async () => {
const body = `See http://127.0.0.1/o/r/pulls/9 for context. ${"y".repeat(900)}`;
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 201, body: createdComment({ body }) },
]);
const { stdout } = await runCliTest(["issue", "comment", "42", "--body", body], {
env: testModeEnv(server.url),
});
expect(stdout).toContain("PR#9");
});
it("suggests viewing the thread when the target is an issue", async () => {
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 201, body: createdComment() },
]);
const { stdout } = await runCliTest(["issue", "comment", "42", "--body", "hi"], {
env: testModeEnv(server.url),
});
expect(stdout).toContain("issue view 42 --comments");
});
it("accepts a pull request number without a type-guard error", async () => {
server = await startFixtureServer([
{
method: "POST",
path: COMMENTS_PATH,
status: 201,
body: createdComment({
pull_request_url: "http://127.0.0.1/testowner/testrepo/pulls/42",
}),
},
]);
const { stdout, exitCode } = await runCliTest(
["issue", "comment", "42", "--body", "Looks good to me."],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).not.toContain("is a pull request");
// The issue is never fetched, so a PR number simply flows through.
expect(server.requests.every((request) => request.method === "POST")).toBe(true);
// `issue view` type-guards PRs, so it must never be suggested for a PR
// target — the suggestion would be a command guaranteed to fail.
expect(stdout).not.toContain("issue view 42");
});
it("rejects a missing body before calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["issue", "comment", "42"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(stdout).toContain("--body");
expect(server.requests).toHaveLength(0);
});
it("rejects a missing issue number before calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["issue", "comment", "--body", "hi"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(server.requests).toHaveLength(0);
});
it("reports a nonexistent issue as ISSUE_NOT_FOUND with exit 1", async () => {
server = await startFixtureServer([
{ method: "POST", path: COMMENTS_PATH, status: 404, body: { message: "Not Found" } },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "comment", "42", "--body", "hi"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(1);
expect(stdout).toContain("code: ISSUE_NOT_FOUND");
});
it("prints help with --help without calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["issue", "comment", "--help"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("usage: gitea-axi issue comment <number>");
expect(server.requests).toHaveLength(0);
});
});

353
test/issue-create.test.ts Normal file
View File

@@ -0,0 +1,353 @@
import { afterEach, describe, expect, it } from "vitest";
import { startFixtureServer, type FixtureServer } from "./fixture-server.js";
import { postedBody, runCliTest, tempFiles, testModeEnv } from "./harness.js";
const ISSUES_PATH = "/api/v1/repos/testowner/testrepo/issues";
const LABELS_PATH = "/api/v1/repos/testowner/testrepo/labels";
const MILESTONES_PATH = "/api/v1/repos/testowner/testrepo/milestones";
let server: FixtureServer;
const files = tempFiles();
afterEach(async () => {
await server.close();
files.cleanup();
});
function createdIssue(fields: Record<string, unknown> = {}): Record<string, unknown> {
return {
number: 7,
title: "Fix the thing",
state: "open",
html_url: "http://127.0.0.1/testowner/testrepo/issues/7",
user: { login: "alexion" },
created_at: "2026-07-01T00:00:00Z",
body: "",
labels: [],
assignees: [],
...fields,
};
}
/** The single POST the CLI sent to the issues endpoint. */
function postedIssue(): Record<string, unknown> {
return postedBody(server, ISSUES_PATH);
}
describe("issue create", () => {
it("creates an issue and renders number, title, state, and url", async () => {
server = await startFixtureServer([
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "Fix the thing"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).toContain("issue:");
expect(stdout).toContain("number: 7");
expect(stdout).toContain("title: Fix the thing");
expect(stdout).toContain("state: open");
// TOON quotes the URL because it contains the key/value separator.
expect(stdout).toContain('url: "http://127.0.0.1/testowner/testrepo/issues/7"');
expect(postedIssue()).toEqual({ title: "Fix the thing" });
});
it("suggests viewing the issue it just created, with the real number", async () => {
server = await startFixtureServer([
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { stdout } = await runCliTest(["issue", "create", "--title", "Fix the thing"], {
env: testModeEnv(server.url),
});
expect(stdout).toContain("issue view 7");
});
it("sends the body from --body", async () => {
server = await startFixtureServer([
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--body", "Some details."],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedIssue()).toEqual({ title: "T", body: "Some details." });
});
it("reads the body from --body-file", async () => {
const path = files.write("body.md", "From a file.\nSecond line.\n");
server = await startFixtureServer([
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--body-file", path],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedIssue()).toEqual({ title: "T", body: "From a file.\nSecond line.\n" });
});
it("rejects --body and --body-file together before calling the API", async () => {
const path = files.write("body.md", "x");
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--body", "x", "--body-file", path],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(server.requests).toHaveLength(0);
});
it("reports an unreadable --body-file as VALIDATION_ERROR", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--body-file", "/nonexistent/nope.md"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(server.requests).toHaveLength(0);
});
it("rejects a missing --title before calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["issue", "create"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(stdout).toContain("--title");
expect(server.requests).toHaveLength(0);
});
it("resolves repeated --label names to ids, case-insensitively", async () => {
server = await startFixtureServer([
{
method: "GET",
path: LABELS_PATH,
body: [
{ id: 11, name: "bug" },
{ id: 22, name: "Priority: High" },
{ id: 33, name: "chore" },
],
},
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--label", "BUG", "--label", "priority: high"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedIssue()).toEqual({ title: "T", labels: [11, 22] });
});
it("rejects an unknown --label name with VALIDATION_ERROR and creates nothing", async () => {
server = await startFixtureServer([
{ method: "GET", path: LABELS_PATH, body: [{ id: 11, name: "bug" }] },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--label", "nope"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(stdout).toContain("nope");
expect(server.requests.some((request) => request.method === "POST")).toBe(false);
});
it("finds a label that only appears on a later page of labels", async () => {
const firstPage = Array.from({ length: 50 }, (_, index) => ({
id: index + 1,
name: `filler-${index}`,
}));
server = await startFixtureServer([
{ method: "GET", path: LABELS_PATH, query: { page: "1" }, body: firstPage },
{
method: "GET",
path: LABELS_PATH,
query: { page: "2" },
body: [{ id: 99, name: "needle" }],
},
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--label", "needle"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedIssue()).toEqual({ title: "T", labels: [99] });
});
it("surfaces a failure to list labels", async () => {
server = await startFixtureServer([
{ method: "GET", path: LABELS_PATH, status: 403, body: { message: "forbidden" } },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--label", "bug"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(1);
expect(stdout).toContain("code: FORBIDDEN");
expect(server.requests.some((request) => request.method === "POST")).toBe(false);
});
it("surfaces a failure to list milestones", async () => {
server = await startFixtureServer([
{ method: "GET", path: MILESTONES_PATH, status: 403, body: { message: "forbidden" } },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--milestone", "v1.0"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(1);
expect(stdout).toContain("code: FORBIDDEN");
expect(server.requests.some((request) => request.method === "POST")).toBe(false);
});
it("renders empty extra fields when the issue has no labels, assignees, or milestone", async () => {
server = await startFixtureServer([
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue({ labels: null }) },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--fields", "labels,assignees,milestone"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(stdout).toContain('labels: ""');
expect(stdout).toContain('assignees: ""');
expect(stdout).toContain('milestone: ""');
});
it("resolves --milestone to its id, case-insensitively", async () => {
server = await startFixtureServer([
{
method: "GET",
path: MILESTONES_PATH,
query: { name: "v1.0" },
body: [{ id: 5, title: "V1.0" }],
},
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--milestone", "v1.0"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedIssue()).toEqual({ title: "T", milestone: 5 });
});
it("rejects an unknown --milestone name with VALIDATION_ERROR and creates nothing", async () => {
server = await startFixtureServer([
{ method: "GET", path: MILESTONES_PATH, body: [] },
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--milestone", "ghost"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(stdout).toContain("ghost");
expect(server.requests.some((request) => request.method === "POST")).toBe(false);
});
it("passes --assignee through as an assignees list", async () => {
server = await startFixtureServer([
{ method: "POST", path: ISSUES_PATH, status: 201, body: createdIssue() },
]);
const { exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--assignee", "alexion"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
expect(postedIssue()).toEqual({ title: "T", assignees: ["alexion"] });
});
it("appends the extra fields named by --fields", async () => {
server = await startFixtureServer([
{
method: "POST",
path: ISSUES_PATH,
status: 201,
body: createdIssue({
body: "The body.",
labels: [{ id: 11, name: "bug" }, { id: 22, name: "chore" }],
assignees: [{ login: "alexion" }],
milestone: { id: 5, title: "v1.0" },
}),
},
]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--fields", "labels,assignees,milestone,body"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(0);
// TOON quotes the joined labels because they contain its list delimiter.
expect(stdout).toContain('labels: "bug, chore"');
expect(stdout).toContain("assignees: alexion");
expect(stdout).toContain("milestone: v1.0");
expect(stdout).toContain("body: The body.");
// The default fields stay in place alongside the requested extras.
expect(stdout).toContain("number: 7");
});
it("rejects an unknown --fields name with VALIDATION_ERROR", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(
["issue", "create", "--title", "T", "--fields", "nonsense"],
{ env: testModeEnv(server.url) },
);
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(stdout).toContain("nonsense");
expect(server.requests).toHaveLength(0);
});
it("surfaces a server-side rejection of the create", async () => {
server = await startFixtureServer([
{
method: "POST",
path: ISSUES_PATH,
status: 422,
body: { message: "title is empty" },
},
]);
const { stdout, exitCode } = await runCliTest(["issue", "create", "--title", "T"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(2);
expect(stdout).toContain("code: VALIDATION_ERROR");
expect(stdout).toContain("title is empty");
});
it("prints help with --help without calling the API", async () => {
server = await startFixtureServer([]);
const { stdout, exitCode } = await runCliTest(["issue", "create", "--help"], {
env: testModeEnv(server.url),
});
expect(exitCode).toBe(0);
expect(stdout).toContain("usage: gitea-axi issue create");
expect(server.requests).toHaveLength(0);
});
});