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

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