Files
liqa/server/test/import.spec.ts
T
Andrii Arsenin 7418adf385 feat(import): add central yaml import for all exportable kinds
- add POST /import, an import page and the import_yaml mcp tool; items
  are validated up front and imported in dependency order
- switch list page import buttons to the central import
- write scenario exports as separate --- yaml documents per entity
- give each test app its own files dir to avoid cross-suite races
- use node: prefix for node built-in imports
- bump version to 1.18.0
2026-09-30 19:25:03 +03:00

220 lines
6.6 KiB
TypeScript

/**
* Integration tests for the central import (`POST /import`) and the
* multi-document YAML scenario export it reads back.
*/
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import { DataSource } from "typeorm";
import { parseAllDocuments } from "yaml";
import { buildTestApp } from "./app.harness";
import { CredentialEntity } from "../src/credential/credential.entity";
import { EnvironmentEntity } from "../src/environment/environment.entity";
import { ScenarioService } from "../src/scenario/scenario.service";
describe("Central import", () => {
let app: INestApplication;
let dataSource: DataSource;
let scenarioService: ScenarioService;
beforeAll(async () => {
app = await buildTestApp();
dataSource = app.get(DataSource);
scenarioService = app.get(ScenarioService);
});
afterAll(async () => {
await app.close();
});
const uniq = () => Math.random().toString(36).slice(2, 8);
function postYaml(yaml: string) {
return request(app.getHttpServer())
.post("/import")
.set("Content-Type", "application/yaml")
.send(yaml);
}
it("imports every kind from a multi-document YAML in dependency order", async () => {
const envId = crypto.randomUUID();
const credId = crypto.randomUUID();
const snippetAlias = `imp-${uniq()}`;
// Scenario first in the file: it references the environment and credential
const yaml = `---
kind: scenario
name: imported-${uniq()}
version: 1
environmentId: ${envId}
credentials:
- credentialId: ${credId}
alias: main
steps:
- title: use snippet
execCode: return context.runSnippet("${snippetAlias}");
---
kind: snippet
alias: ${snippetAlias}
title: Imported snippet
version: 2
code: return 1;
---
kind: credential
id: ${credId}
name: imported-cred
data: '{"token":"t"}'
---
kind: environment
id: ${envId}
name: imported-env-${uniq()}
data:
base_url: https://example.test
`;
const res = await postYaml(yaml).expect(201);
const kinds = res.body.imported.map((i: { kind: string }) => i.kind);
expect(kinds).toEqual(["environment", "credential", "snippet", "scenario"]);
const scenario = res.body.imported[3];
expect(scenario.version).toBe(1);
const sc = await scenarioService.findOne(scenario.id);
expect(sc.environmentId).toBe(envId);
expect(sc.scenarioCredentials.map((c) => c.credentialId)).toEqual([credId]);
expect(res.body.imported[2]).toMatchObject({
name: snippetAlias,
version: 2,
});
});
it("accepts a document holding a list of items", async () => {
const yaml = `- kind: credential
name: list-a-${uniq()}
- kind: credential
name: list-b-${uniq()}
`;
const res = await postYaml(yaml).expect(201);
expect(res.body.imported).toHaveLength(2);
});
it("accepts a JSON array", async () => {
const res = await request(app.getHttpServer())
.post("/import")
.send([{ kind: "credential", name: `json-${uniq()}` }])
.expect(201);
expect(res.body.imported[0].kind).toBe("credential");
});
it("imports nothing when any item is invalid", async () => {
const envName = `not-imported-${uniq()}`;
const yaml = `---
kind: environment
name: ${envName}
data: {}
---
kind: snippet
alias: no-version-${uniq()}
code: return 1;
---
kind: gadget
name: what
`;
const res = await postYaml(yaml).expect(400);
const message = JSON.stringify(res.body);
expect(message).toContain("Item 2 (snippet)");
expect(message).toContain("version");
expect(message).toContain("Item 3");
const envRepo = dataSource.getRepository(EnvironmentEntity);
expect(await envRepo.findOneBy({ name: envName })).toBeNull();
});
it("rejects invalid YAML", async () => {
const res = await postYaml("kind: scenario\n bad: [indent").expect(400);
expect(JSON.stringify(res.body)).toContain("YAML document 1");
});
it("rejects an empty body", async () => {
await postYaml("").expect(400);
});
describe("scenario export round trip", () => {
it("exports one YAML document per entity and imports it back", async () => {
const envRepo = dataSource.getRepository(EnvironmentEntity);
const env = await envRepo.save(
envRepo.create({ name: `rt-env-${uniq()}`, data: { a: "1" } }),
);
const credRepo = dataSource.getRepository(CredentialEntity);
const cred = await credRepo.save(
credRepo.create({ name: "rt-cred", data: null }),
);
const sc = await scenarioService.create({
name: `rt-${uniq()}`,
environmentId: env.id,
});
await scenarioService.createStep(sc.id, { execCode: "return 1;" });
await scenarioService.addScenarioCredential(sc.id, {
credentialId: cred.id,
alias: "c",
});
const exported = await request(app.getHttpServer())
.get(
`/scenarios/${sc.id}/export?includeEnvironment=true&credentialIds=${cred.id}`,
)
.expect(200);
const docs = parseAllDocuments(exported.text);
expect(docs.map((d) => d.errors)).toEqual([[], [], []]);
expect(docs.map((d) => (d.toJS() as { kind: string }).kind)).toEqual([
"environment",
"credential",
"scenario",
]);
const res = await postYaml(exported.text).expect(201);
expect(res.body.imported.map((i: { id: string }) => i.id)).toEqual([
env.id,
cred.id,
sc.id,
]);
});
});
describe("import_yaml MCP tool", () => {
async function mcpCall(name: string, args: Record<string, unknown>) {
const res = await request(app.getHttpServer())
.post("/mcp")
.set("Accept", "application/json, text/event-stream")
.send({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name, arguments: args },
});
const text = res.text.startsWith("event:")
? res.text
.split("\n")
.find((l) => l.startsWith("data:"))!
.slice(5)
: res.text;
return JSON.parse(text).result as {
isError?: boolean;
content: { text: string }[];
};
}
it("imports items from YAML text", async () => {
const result = await mcpCall("import_yaml", {
yaml: `kind: credential\nname: mcp-${uniq()}\n`,
});
expect(result.isError).toBeFalsy();
expect(JSON.parse(result.content[0].text).imported).toHaveLength(1);
});
it("returns the validation errors as an MCP error", async () => {
const result = await mcpCall("import_yaml", {
yaml: `kind: snippet\nalias: x\ncode: return 1;\n`,
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain("version");
});
});
});