ui-steps-api-servers.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /**
  2. * `GET /api/steps` on servers: an Express API, a NestJS API, a FastAPI service
  3. * and a Spring controller, in one indexed fixture, shaped to cross every
  4. * boundary an endpoint's picture has — the request and what runs before the
  5. * handler, the database, a queue, an email, and the responses with their
  6. * status codes. Mirrors `ui-steps-api.test.ts` (the mobile app).
  7. */
  8. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  9. import * as fs from 'fs';
  10. import * as os from 'os';
  11. import * as path from 'path';
  12. import { CodeGraph } from '../src';
  13. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  14. import { buildSteps, projectKind } from '../src/ui-server/api/steps';
  15. import { routeRoots } from '../src/ui-server/api/route-roots';
  16. let tmpDir: string;
  17. let cg: CodeGraph;
  18. function write(rel: string, content: string): void {
  19. const full = path.join(tmpDir, rel);
  20. fs.mkdirSync(path.dirname(full), { recursive: true });
  21. fs.writeFileSync(full, content);
  22. }
  23. beforeAll(async () => {
  24. await initGrammars();
  25. await loadAllGrammars();
  26. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ui-steps-servers-'));
  27. write(
  28. 'package.json',
  29. JSON.stringify({ name: 'api', dependencies: { express: '4', '@nestjs/core': '10', '@nestjs/common': '10', bullmq: '5', '@prisma/client': '5', typeorm: '0.3' } })
  30. );
  31. // ---- Express: a named handler behind middleware, and an inline handler.
  32. write('src/server/db.ts', "import { PrismaClient } from '@prisma/client'\nexport const prisma = new PrismaClient()\n");
  33. write('src/server/queue.ts', "import { Queue } from 'bullmq'\nexport const emailQueue = new Queue('email')\n");
  34. write('src/server/errors.ts', 'export class NotFoundError extends Error {}\n');
  35. write('src/server/auth.ts', 'export function authenticate(req, res, next) {\n next()\n}\n');
  36. write('src/server/validate.ts', 'export function validate(schema) {\n return (req, res, next) => next()\n}\n');
  37. write(
  38. 'src/server/users.service.ts',
  39. "import { prisma } from './db'\n" +
  40. "import { emailQueue } from './queue'\n" +
  41. "import { NotFoundError } from './errors'\n" +
  42. 'export async function createUser(req, res) {\n' +
  43. ' const user = await prisma.user.create({ data: { email: req.body.email, name: req.body.name } })\n' +
  44. " await emailQueue.add('welcome', { userId: user.id })\n" +
  45. ' if (!user.verified) {\n' +
  46. ' await sendVerification(user)\n' +
  47. ' }\n' +
  48. ' res.status(201).json(user)\n' +
  49. '}\n' +
  50. 'export async function getUser(id: string) {\n' +
  51. ' const user = await prisma.user.findUnique({ where: { id } })\n' +
  52. " if (!user) throw new NotFoundError('no such user')\n" +
  53. ' return user\n' +
  54. '}\n' +
  55. 'async function sendVerification(user) {\n' +
  56. ' await transporter.sendMail({ to: user.email })\n' +
  57. '}\n'
  58. );
  59. write(
  60. 'src/server/users.routes.ts',
  61. "import { Router } from 'express'\n" +
  62. "import { authenticate } from './auth'\n" +
  63. "import { validate } from './validate'\n" +
  64. "import { createUser, getUser } from './users.service'\n" +
  65. 'const router = Router()\n' +
  66. "router.post('/users', authenticate, validate(userSchema), createUser)\n" +
  67. "router.get('/users/:id', authenticate, async (req, res) => {\n" +
  68. ' const user = await getUser(req.params.id)\n' +
  69. ' res.json(user)\n' +
  70. '})\n' +
  71. 'export default router\n'
  72. );
  73. // ---- NestJS: guards on the class and the method, DI into a service, a queue consumer.
  74. write(
  75. 'src/nest/cats.service.ts',
  76. "import { Injectable } from '@nestjs/common'\n" +
  77. "import { InjectRepository } from '@nestjs/typeorm'\n" +
  78. "import { Repository } from 'typeorm'\n" +
  79. "import { InjectQueue } from '@nestjs/bullmq'\n" +
  80. "import { Queue } from 'bullmq'\n" +
  81. "import { Cat } from './cat.entity'\n" +
  82. '@Injectable()\n' +
  83. 'export class CatsService {\n' +
  84. ' constructor(\n' +
  85. ' @InjectRepository(Cat) private readonly catsRepository: Repository<Cat>,\n' +
  86. " @InjectQueue('cats') private readonly catsQueue: Queue\n" +
  87. ' ) {}\n' +
  88. ' async create(dto) {\n' +
  89. ' const cat = await this.catsRepository.save(dto)\n' +
  90. " await this.catsQueue.add('index', { id: cat.id })\n" +
  91. ' return cat\n' +
  92. ' }\n' +
  93. ' async findOne(id: string) {\n' +
  94. ' return this.catsRepository.findOne({ where: { id } })\n' +
  95. ' }\n' +
  96. '}\n'
  97. );
  98. write('src/nest/cat.entity.ts', "import { Entity } from 'typeorm'\n@Entity()\nexport class Cat {\n id: string\n}\n");
  99. write(
  100. 'src/nest/cats.controller.ts',
  101. "import { Controller, Get, Post, Body, Param, UseGuards, NotFoundException } from '@nestjs/common'\n" +
  102. "import { AuthGuard } from '@nestjs/passport'\n" +
  103. "import { CatsService } from './cats.service'\n" +
  104. "import { RolesGuard } from './roles.guard'\n" +
  105. "@Controller('cats')\n" +
  106. "@UseGuards(AuthGuard('jwt'))\n" +
  107. 'export class CatsController {\n' +
  108. ' constructor(private readonly catsService: CatsService) {}\n' +
  109. ' @Post()\n' +
  110. ' @UseGuards(RolesGuard)\n' +
  111. ' async create(@Body() dto: CreateCatDto) {\n' +
  112. ' return this.catsService.create(dto)\n' +
  113. ' }\n' +
  114. " @Get(':id')\n" +
  115. " async findOne(@Param('id') id: string) {\n" +
  116. ' const cat = await this.catsService.findOne(id)\n' +
  117. " if (!cat) throw new NotFoundException('no cat')\n" +
  118. ' return cat\n' +
  119. ' }\n' +
  120. '}\n'
  121. );
  122. write('src/nest/roles.guard.ts', "import { Injectable } from '@nestjs/common'\n@Injectable()\nexport class RolesGuard {\n canActivate() { return true }\n}\n");
  123. write(
  124. 'src/nest/cats.processor.ts',
  125. "import { Processor, Process } from '@nestjs/bull'\n" +
  126. "@Processor('cats')\n" +
  127. 'export class CatsProcessor {\n' +
  128. " @Process('index')\n" +
  129. ' async handleIndex(job) {\n' +
  130. ' await searchClient.index(job.data)\n' +
  131. ' }\n' +
  132. '}\n'
  133. );
  134. // ---- FastAPI: a dependency on the route, SQLModel, an HTTPException, a Celery task.
  135. write(
  136. 'api/items.py',
  137. 'from fastapi import APIRouter, Depends, HTTPException\n' +
  138. 'from sqlmodel import select\n' +
  139. 'from .deps import get_current_user, SessionDep\n' +
  140. 'from .models import Item, ItemCreate\n' +
  141. 'from .tasks import send_welcome\n' +
  142. '\n' +
  143. 'router = APIRouter()\n' +
  144. '\n' +
  145. '@router.post("/items", dependencies=[Depends(get_current_user)])\n' +
  146. 'def create_item(session: SessionDep, item_in: ItemCreate):\n' +
  147. ' item = Item.model_validate(item_in)\n' +
  148. ' session.add(item)\n' +
  149. ' session.commit()\n' +
  150. ' if item.price < 0:\n' +
  151. ' raise HTTPException(status_code=422, detail="bad price")\n' +
  152. ' send_welcome.delay(item.id)\n' +
  153. ' return item\n'
  154. );
  155. write('api/deps.py', 'def get_current_user():\n return None\n\nSessionDep = None\n');
  156. write('api/models.py', 'class Item:\n pass\n\nclass ItemCreate:\n pass\n');
  157. write('api/tasks.py', 'from celery import shared_task\n\n@shared_task\ndef send_welcome(item_id):\n return item_id\n');
  158. // A router with its own prefix, included by an aggregate router, mounted at a literal prefix — and one at a computed one.
  159. write(
  160. 'api/orders.py',
  161. 'from fastapi import APIRouter\n' +
  162. '\n' +
  163. 'router = APIRouter(prefix="/orders", tags=["orders"])\n' +
  164. '\n' +
  165. '@router.get("/")\n' +
  166. 'def list_orders():\n' +
  167. ' return []\n' +
  168. '\n' +
  169. '@router.get("/{order_id}")\n' +
  170. 'def get_order(order_id: int):\n' +
  171. ' return order_id\n'
  172. );
  173. write('api/v1.py', 'from fastapi import APIRouter\nfrom .orders import router as orders_router\napi_router = APIRouter()\napi_router.include_router(orders_router)\n');
  174. write(
  175. 'api/main.py',
  176. 'from fastapi import FastAPI\nfrom .items import router\nfrom .v1 import api_router\nfrom .config import settings\napp = FastAPI()\napp.include_router(router)\napp.include_router(api_router, prefix="/api/v1")\napp.include_router(api_router, prefix=settings.LEGACY)\n'
  177. );
  178. write('api/config.py', 'settings = None\n');
  179. write('requirements.txt', 'fastapi\nsqlmodel\ncelery\n');
  180. // ---- Spring: a repository typed on a field, ResponseEntity replies, a guard annotation.
  181. write(
  182. 'src/main/java/demo/OwnerController.java',
  183. 'package demo;\n' +
  184. 'import org.springframework.web.bind.annotation.*;\n' +
  185. 'import org.springframework.http.*;\n' +
  186. '@RestController\n' +
  187. '@RequestMapping("/owners")\n' +
  188. 'public class OwnerController {\n' +
  189. ' private final OwnerRepository owners;\n' +
  190. ' public OwnerController(OwnerRepository owners) { this.owners = owners; }\n' +
  191. ' @PostMapping("/new")\n' +
  192. ' @PreAuthorize("hasRole(\'ADMIN\')")\n' +
  193. ' public ResponseEntity<Owner> create(@RequestBody Owner owner) {\n' +
  194. ' if (owner.getName() == null) {\n' +
  195. ' return ResponseEntity.badRequest().build();\n' +
  196. ' }\n' +
  197. ' Owner saved = owners.save(owner);\n' +
  198. ' return ResponseEntity.status(HttpStatus.CREATED).body(saved);\n' +
  199. ' }\n' +
  200. '}\n'
  201. );
  202. write(
  203. 'src/main/java/demo/OwnerRepository.java',
  204. 'package demo;\nimport org.springframework.data.jpa.repository.JpaRepository;\npublic interface OwnerRepository extends JpaRepository<Owner, Integer> {\n}\n'
  205. );
  206. write('src/main/java/demo/Owner.java', 'package demo;\npublic class Owner {\n private String name;\n public String getName() { return name; }\n}\n');
  207. // ---- ASP.NET Minimal API, endpoint-group style: the class is the group,
  208. // the handler is the first argument, the app's extension supplies `/api/`.
  209. write(
  210. 'src/Web/Endpoints/TodoItems.cs',
  211. 'using Microsoft.AspNetCore.Http.HttpResults;\n' +
  212. 'namespace Demo.Web.Endpoints;\n' +
  213. 'public class TodoItems : IEndpointGroup\n' +
  214. '{\n' +
  215. ' public static void Map(RouteGroupBuilder groupBuilder)\n' +
  216. ' {\n' +
  217. ' groupBuilder.RequireAuthorization();\n' +
  218. ' groupBuilder.MapPost(CreateTodoItem);\n' +
  219. ' groupBuilder.MapPut(UpdateTodoItem, "{id}");\n' +
  220. ' }\n' +
  221. ' public static async Task<Created<int>> CreateTodoItem(ISender sender, CreateTodoItemCommand command)\n' +
  222. ' {\n' +
  223. ' var id = await sender.Send(command);\n' +
  224. ' return TypedResults.Created($"/{nameof(TodoItems)}/{id}", id);\n' +
  225. ' }\n' +
  226. ' public static async Task<Results<NoContent, BadRequest>> UpdateTodoItem(ISender sender, int id, UpdateTodoItemCommand command)\n' +
  227. ' {\n' +
  228. ' if (id != command.Id)\n' +
  229. ' return TypedResults.BadRequest();\n' +
  230. ' await sender.Send(command);\n' +
  231. ' return TypedResults.NoContent();\n' +
  232. ' }\n' +
  233. '}\n'
  234. );
  235. write(
  236. 'src/Web/Infrastructure/WebApplicationExtensions.cs',
  237. 'using Microsoft.AspNetCore.Builder;\n' +
  238. 'namespace Demo.Web.Infrastructure;\n' +
  239. 'public static class WebApplicationExtensions\n' +
  240. '{\n' +
  241. ' public static WebApplication MapEndpoints(this WebApplication app)\n' +
  242. ' {\n' +
  243. ' var groupName = "x";\n' +
  244. ' var group = app.MapGroup($"/api/{groupName}").WithTags(groupName);\n' +
  245. ' return app;\n' +
  246. ' }\n' +
  247. '}\n'
  248. );
  249. cg = CodeGraph.initSync(tmpDir);
  250. await cg.indexAll();
  251. });
  252. afterAll(() => {
  253. cg?.close();
  254. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  255. });
  256. const q = (params: Record<string, string>) => new URLSearchParams(params);
  257. const route = (name: string) => {
  258. const r = cg.getNodesByKind('route').find((r) => r.name === name);
  259. if (!r) throw new Error(`no route ${name}: ${cg.getNodesByKind('route').map((r) => r.name).join(', ')}`);
  260. return r;
  261. };
  262. const effect = (p: Awaited<ReturnType<typeof buildSteps>>, category: string) => p.steps.find((s) => s.kind === 'effect' && s.effect?.category === category);
  263. describe('route roots', () => {
  264. it('names the handler an API route runs, the route itself for an inline handler', () => {
  265. const roots = routeRoots(cg, cg.getNodesByKind('route'));
  266. expect(roots.get(route('POST /users').id)).toMatchObject({ inline: false, node: { name: 'createUser' } });
  267. expect(roots.get(route('GET /users/:id').id)).toMatchObject({ inline: true });
  268. expect(roots.get(route('POST /cats').id)?.node.qualifiedName).toContain('CatsController');
  269. expect(roots.get(route('POST /items').id)?.node.name).toBe('create_item');
  270. expect(roots.get(route('POST /owners/new').id)?.node.name).toBe('create');
  271. });
  272. it('calls the project an API', () => {
  273. expect(projectKind(cg.getNodesByKind('route'), 0)).toBe('api');
  274. });
  275. });
  276. describe('Express', () => {
  277. it('draws the handler’s database write, the queue job, the email, and the 201 — after the middleware', async () => {
  278. const p = await buildSteps(cg, tmpDir, q({ anchor: route('POST /users').id }));
  279. expect(p.project).toBe('api');
  280. const anchor = p.steps.find((s) => s.anchor)!;
  281. expect(anchor.kind).toBe('screen');
  282. expect(anchor.sub).toBe('createUser');
  283. expect(anchor.screen).toMatchObject({ path: 'POST /users', endpoint: true, inline: false, component: { name: 'createUser' } });
  284. expect(anchor.trigger).toEqual({ kind: 'request', name: 'POST', of: '/users', in: 'users.routes.ts', after: ['authenticate', 'validate(…)'] });
  285. const db = effect(p, 'database')!;
  286. expect(db.label).toBe('prisma.user.create({ data })');
  287. expect(db.effect).toMatchObject({ model: 'user', access: 'write', by: { name: 'createUser' } });
  288. expect(db.sub).toBe('database · user · write · createUser');
  289. const queue = effect(p, 'queue')!;
  290. expect(queue.label).toBe("emailQueue.add('welcome', { userId })");
  291. const mail = effect(p, 'email')!;
  292. expect(mail.label).toBe('transporter.sendMail({ to })');
  293. const mailLink = p.links.find((l) => l.to === mail.id)!;
  294. expect(mailLink.via.map((v) => v.name)).toEqual(['sendVerification']);
  295. expect(mailLink.when).toBe('!user.verified');
  296. const res = effect(p, 'response')!;
  297. expect(res.label).toBe('201');
  298. expect(res.effect?.statuses).toEqual([201]);
  299. const resLink = p.links.find((l) => l.to === res.id)!;
  300. expect(resLink.sites[0]).toMatchObject({ text: 'res.status(201).json', args: 'user', status: 201 });
  301. });
  302. it('walks an inline handler as the route itself, into the service’s read and its 404', async () => {
  303. const p = await buildSteps(cg, tmpDir, q({ anchor: route('GET /users/:id').id }));
  304. const anchor = p.steps.find((s) => s.anchor)!;
  305. expect(anchor.sub).toBe('inline handler · users.routes.ts');
  306. expect(anchor.trigger).toMatchObject({ kind: 'request', name: 'GET', of: '/users/:id', after: ['authenticate'] });
  307. const db = effect(p, 'database')!;
  308. expect(db.effect).toMatchObject({ model: 'user', access: 'read', by: { name: 'getUser' } });
  309. const res = effect(p, 'response')!;
  310. expect(res.label).toBe('404');
  311. const resLink = p.links.find((l) => l.to === res.id)!;
  312. expect(resLink.sites[0]).toMatchObject({ text: 'NotFoundError', status: 404, when: '!user' });
  313. expect(resLink.via.map((v) => v.name)).toEqual(['getUser']);
  314. });
  315. });
  316. describe('NestJS', () => {
  317. it('reads the guards on the class and the method, follows DI into the repository and the queue', async () => {
  318. const p = await buildSteps(cg, tmpDir, q({ anchor: route('POST /cats').id }));
  319. const anchor = p.steps.find((s) => s.anchor)!;
  320. expect(anchor.sub).toBe('create');
  321. expect(anchor.trigger).toEqual({ kind: 'request', name: 'POST', of: '/cats', in: 'cats.controller.ts', after: ["UseGuards(AuthGuard('jwt'))", 'UseGuards(RolesGuard)'] });
  322. const db = effect(p, 'database')!;
  323. expect(db.label).toBe('this.catsRepository.save(dto)');
  324. expect(db.effect).toMatchObject({ model: 'cats', access: 'write', by: { name: 'create' } });
  325. const dbLink = p.links.find((l) => l.to === db.id)!;
  326. expect(dbLink.via.map((v) => v.name)).toEqual(['create']);
  327. // The job put on the `cats` queue lands on the processor that consumes it
  328. // — an arrival, not a call outside the index; the site is the `add` as written.
  329. expect(effect(p, 'queue')).toBeUndefined();
  330. const landing = p.steps.find((s) => s.kind === 'event' && s.node?.name === 'handleIndex')!;
  331. expect(landing).toBeDefined();
  332. expect(landing.event).toBe('index');
  333. expect(landing.trigger).toEqual({ kind: 'decorator', name: 'Process', of: "'index'", in: 'cats.processor.ts' });
  334. const toLanding = p.links.find((l) => l.to === landing.id)!;
  335. expect(toLanding.kind).toBe('event');
  336. expect(toLanding.synthesized).toBe(true);
  337. expect(toLanding.sites[0]).toMatchObject({ text: 'this.catsQueue.add', args: "'index', { id }" });
  338. expect(toLanding.label).toBe('via queue-job · job index · queue cats · registered at src/nest/cats.processor.ts:4');
  339. });
  340. it('a thrown exception is the 404 the request gets', async () => {
  341. const p = await buildSteps(cg, tmpDir, q({ anchor: route('GET /cats/:id').id }));
  342. const res = effect(p, 'response')!;
  343. expect(res.label).toBe('404');
  344. const resLink = p.links.find((l) => l.to === res.id)!;
  345. expect(resLink.sites[0]).toMatchObject({ text: 'NotFoundException', args: "'no cat'", status: 404, when: '!cat' });
  346. expect(effect(p, 'database')?.effect).toMatchObject({ access: 'read' });
  347. });
  348. it('a queue consumer says the job that fires it', async () => {
  349. const p = await buildSteps(cg, tmpDir, q({ symbol: 'handleIndex' }));
  350. expect(p.steps.find((s) => s.anchor)?.trigger).toEqual({ kind: 'decorator', name: 'Process', of: "'index'", in: 'cats.processor.ts' });
  351. });
  352. });
  353. describe('FastAPI', () => {
  354. it('names a mounted router’s routes by the path a request takes — the include prefix, then the router’s own', () => {
  355. const names = cg.getNodesByKind('route').map((r) => r.name);
  356. expect(names).toContain('GET /api/v1/orders');
  357. expect(names).toContain('GET /api/v1/orders/{order_id}');
  358. expect(names).toContain('POST /items');
  359. expect(names).not.toContain('GET /');
  360. });
  361. it('reads the dependency on the route, the session writes, the 422 and the Celery task', async () => {
  362. const p = await buildSteps(cg, tmpDir, q({ anchor: route('POST /items').id }));
  363. const anchor = p.steps.find((s) => s.anchor)!;
  364. expect(anchor.sub).toBe('create_item');
  365. expect(anchor.trigger).toEqual({ kind: 'request', name: 'POST', of: '/items', in: 'items.py', after: ['Depends(get_current_user)'] });
  366. const db = effect(p, 'database')!;
  367. expect(db.effect?.apis).toEqual(['session.add', 'session.commit']);
  368. expect(db.effect).toMatchObject({ access: 'write' });
  369. const res = effect(p, 'response')!;
  370. expect(res.label).toBe('422');
  371. const resLink = p.links.find((l) => l.to === res.id)!;
  372. expect(resLink.sites[0]).toMatchObject({ text: 'HTTPException', args: 'status_code=422, detail="bad price"', status: 422, when: 'item.price < 0' });
  373. const queue = effect(p, 'queue')!;
  374. expect(queue.label).toBe('send_welcome.delay(item.id)');
  375. });
  376. });
  377. describe('ASP.NET endpoint groups', () => {
  378. it('names the group’s routes under the app’s /api/ head and starts the walk at the handler, with its replies', async () => {
  379. const names = cg.getNodesByKind('route').map((r) => r.name);
  380. expect(names).toContain('POST /api/TodoItems');
  381. expect(names).toContain('PUT /api/TodoItems/{id}');
  382. const p = await buildSteps(cg, tmpDir, q({ anchor: route('PUT /api/TodoItems/{id}').id }));
  383. const anchor = p.steps.find((s) => s.anchor)!;
  384. expect(anchor.sub).toBe('UpdateTodoItem');
  385. expect(anchor.trigger).toMatchObject({ kind: 'request', name: 'PUT', of: '/api/TodoItems/{id}' });
  386. const res = effect(p, 'response')!;
  387. expect(res.label).toBe('204 · 400');
  388. const rows = p.links.find((l) => l.to === res.id)!.sites.map((s) => [s.status, s.when]);
  389. expect(rows).toEqual([
  390. [400, 'id != command.Id'],
  391. [204, 'id == command.Id'],
  392. ]);
  393. });
  394. });
  395. describe('Spring', () => {
  396. it('types the repository off the field, reads the annotation guard, and both replies with their codes', async () => {
  397. const p = await buildSteps(cg, tmpDir, q({ anchor: route('POST /owners/new').id }));
  398. const anchor = p.steps.find((s) => s.anchor)!;
  399. expect(anchor.sub).toBe('create');
  400. expect(anchor.trigger).toEqual({ kind: 'request', name: 'POST', of: '/owners/new', in: 'OwnerController.java', after: ["PreAuthorize(\"hasRole('ADMIN')\")"] });
  401. const db = effect(p, 'database')!;
  402. expect(db.label).toBe('owners.save(owner)');
  403. expect(db.effect).toMatchObject({ model: 'Owner', access: 'write' });
  404. const dbLink = p.links.find((l) => l.to === db.id)!;
  405. expect(dbLink.when).toBe('owner.getName() != null');
  406. const res = effect(p, 'response')!;
  407. expect(res.label).toBe('201 · 400');
  408. const rows = p.links.find((l) => l.to === res.id)!.sites.map((s) => [s.status, s.when]);
  409. expect(rows).toEqual([
  410. [400, 'owner.getName() == null'],
  411. [201, 'owner.getName() != null'],
  412. ]);
  413. });
  414. });