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

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