@@ -260,5 +260,119 @@ def test_output_template_documents_render_and_its_payload_only() -> None:
260260 assert kinds == {ApiSymbolKind .RENDER , ApiSymbolKind .PAYLOAD }
261261
262262
263+ # ---------------------------------------------------------------------------
264+ # FR-044: a read-only object's unit documents EXACTLY the routes its router mounts.
265+ # ---------------------------------------------------------------------------
266+
267+ _READ_ONLY_MODEL = """
268+ { "metadata.root": { "package": "acme::sales", "children": [
269+ { "object.entity": { "name": "Invoice", "children": [
270+ { "source.rdb": { "@table": "invoices" } },
271+ { "field.long": { "name": "id" } },
272+ { "field.string": { "name": "status", "@required": true, "@maxLength": 20 } },
273+ { "field.long": { "name": "amountCents", "@required": true } },
274+ { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } },
275+ { "dimension.attribute": { "name": "status", "@of": "Invoice.status" } },
276+ { "measure.aggregate": { "name": "invoices", "@agg": "count", "@of": "Invoice.id" } }
277+ ]}},
278+ { "object.projection": { "name": "KeyedSummary", "children": [
279+ { "source.rdb": { "@kind": "view", "@view": "v_keyed_summary" } },
280+ { "field.long": { "name": "id", "extends": "Invoice.id", "@filterable": true } },
281+ { "field.string": { "name": "status", "extends": "Invoice.status", "@filterable": true } },
282+ { "identity.primary": { "name": "pk", "extends": "Invoice.pk" } }
283+ ]}},
284+ { "object.projection": { "name": "KeylessSummary", "children": [
285+ { "source.rdb": { "@kind": "view", "@view": "v_keyless_summary" } },
286+ { "field.string": { "name": "status", "extends": "Invoice.status", "@filterable": true } },
287+ { "field.long": { "name": "amountCents", "extends": "Invoice.amountCents", "@filterable": true } }
288+ ]}},
289+ { "object.report": { "name": "StatusTotals", "@from": "Invoice",
290+ "@dimensions": ["status"], "@measures": ["invoices"],
291+ "children": [ { "source.rdb": { "@kind": "view", "@view": "v_status_totals" } } ]
292+ }}
293+ ]}}
294+ """
295+
296+ _WRITE_VERBS = {"POST" , "PATCH" , "PUT" , "DELETE" }
297+
298+
299+ def _generated_routers_and_docs ():
300+ """Run the real orchestrator (`run_gen`, the path `metaobjects gen` takes) and the real
301+ docs builder over the read-only model; return ``(docs units by node, router source by
302+ snake name)``."""
303+ from metaobjects .codegen .generator_registry import GeneratorBuildContext , list_generators
304+ from metaobjects .codegen .runner import run_gen
305+
306+ with tempfile .TemporaryDirectory () as d :
307+ (Path (d ) / "meta.json" ).write_text (_READ_ONLY_MODEL , encoding = "utf-8" )
308+ loaded = MetaDataLoader .from_directory (d )
309+ assert not loaded .errors , loaded .errors
310+ out = Path (tempfile .mkdtemp (prefix = "py-apidocs-ro-" ))
311+ templates = out / "t"
312+ templates .mkdir ()
313+ gens = [
314+ e .factory (GeneratorBuildContext (template_root = str (templates )))
315+ for e in list_generators ()
316+ if e .name in {"entity" , "routes" , "filter-allowlist" }
317+ ]
318+ run_gen (GenConfig (out_dir = str (out / "o" )), loaded .root , generators = gens )
319+ routers = {p .stem : p .read_text (encoding = "utf-8" ) for p in (out / "o" ).glob ("*_router.py" )}
320+ model = PythonApiModelBuilder ().build (loaded .root , "apidocs-ro" )
321+ return {u .node : u for u in model .units }, routers
322+
323+
324+ def _mounted_routes (router_src : str , prefix : str ) -> set [str ]:
325+ """``"VERB /api/path"`` for every route the router mounts as a WORKING endpoint: a
326+ handler that answers 405 ``method_not_allowed`` is a refusal, not an endpoint."""
327+ import ast
328+
329+ mounted : set [str ] = set ()
330+ for node in ast .walk (ast .parse (router_src )):
331+ if not isinstance (node , ast .FunctionDef ):
332+ continue
333+ refusal = "method_not_allowed" in ast .get_source_segment (router_src , node )
334+ for dec in node .decorator_list :
335+ if (
336+ isinstance (dec , ast .Call )
337+ and isinstance (dec .func , ast .Attribute )
338+ and isinstance (dec .func .value , ast .Name )
339+ and dec .func .value .id == "router"
340+ and not refusal
341+ ):
342+ mounted .add (f"{ dec .func .attr .upper ()} { prefix } { dec .args [0 ].value } " )
343+ return mounted
344+
345+
346+ def _documented_routes (unit ) -> set [str ]:
347+ return {s .name for s in unit .symbols if s .kind == ApiSymbolKind .REST }
348+
349+
350+ @pytest .mark .parametrize (
351+ "node,snake,prefix,has_item" ,
352+ [
353+ ("KeyedSummary" , "keyed_summary" , "/api/keyed_summaries" , True ),
354+ ("KeylessSummary" , "keyless_summary" , "/api/keyless_summaries" , False ),
355+ ("StatusTotals" , "status_totals" , "/api/status_totals" , False ),
356+ ],
357+ )
358+ def test_read_only_unit_documents_exactly_the_routes_its_router_mounts (
359+ node : str , snake : str , prefix : str , has_item : bool
360+ ) -> None :
361+ units , routers = _generated_routers_and_docs ()
362+ router = routers [f"{ snake } _router" ]
363+ documented = _documented_routes (units [node ])
364+ mounted = _mounted_routes (router , prefix )
365+ assert documented == mounted
366+ # Concretely: GET list always; GET by id only with an item route; never a write verb.
367+ assert ("GET " + prefix ) in documented
368+ assert any (r .startswith ("GET " + prefix + "/{" ) for r in documented ) is has_item
369+ assert not {r .split (" " )[0 ] for r in documented } & _WRITE_VERBS
370+ # The seam: `find_by_id` exists iff the by-id route does, and the docs agree.
371+ assert ("def find_by_id(" in router ) is has_item
372+ repo = next (s for s in units [node ].symbols if s .kind == ApiSymbolKind .DATA_ACCESS )
373+ assert ("Optional" in (repo .returns or "" )) is has_item
374+ assert _contains_identifier (router , repo .name )
375+
376+
263377if __name__ == "__main__" : # pragma: no cover
264378 raise SystemExit (pytest .main ([__file__ , "-q" ]))
0 commit comments