Files
floci/tools/docs/test_regen_action_docs.py
T
TiM 7d70f64162 feat(docs): generate Supported Actions tables from handler source (#1641)
* feat(docs): generate Supported Actions tables from handler source

The "Supported Actions" tables in docs/services/*.md were hand-maintained and
drifted from the handlers. For example secrets-manager.md omitted RestoreSecret,
which SecretsManagerJsonHandler dispatches, and acm.md listed RenewCertificate,
which is not implemented anywhere in src/.

Derive the action list from handler source so it cannot drift, while keeping the
hand-written Description column:

- tools/docs/regen_action_docs.py extracts actions from `case "X" ->` switch arms
  (including multi-label arms) and JAX-RS REST controllers, and rewrites only the
  rows between the <!-- floci:actions --> markers. Descriptions are preserved by
  action name; new actions get a "-" placeholder. PascalCase-only matching avoids
  picking up SCREAMING_CASE labels from non-action switches.
- tools/docs/services.yaml registers 18 single-table switch services and lists the
  remaining switch handlers under deferred_handlers, so the new-service sentinel
  fires only on a genuinely unregistered handler.
- make docs-sync / docs-check / docs-test, plus a Python-only CI workflow that
  gates on handler, doc, and tooling changes.
- Migrate 18 service docs into marker blocks, reconciling real drift (adds
  RestoreSecret, ImportCertificate, and others; drops the unimplemented
  RenewCertificate).

Revives the parser and CI gate from #738 by @ericbsantana and completes the
description-preservation its spec described. REST-mode, mixed-mode, multi-table,
non-tabular, S3, and ecr docs are deferred and tracked in deferred_handlers.

* docs: drop standalone design spec from action-docs tooling

Remove ideas/auto-generated-action-tables.spec.md and the four references
to it (CONTRIBUTING.md, Makefile, regen_action_docs.py docstring,
services.yaml). It was a planning artifact; the operational docs live in
CONTRIBUTING.md and the tooling is self-documenting. The #738 / @ericbsantana
credit is preserved in the PR description.

* chore: address review on action-docs tooling

- pin actions/checkout to v7.0.0 in docs-actions workflow to match the
  repo-wide bump (#1690), so dependabot does not immediately flag the new file
- document in the generator docstring that a switch case label counts as
  supported purely by existing, so a per-action UnsupportedOperation stub
  would be a false positive (handlers here reject from the default arm)

* docs: regenerate action tables against current handler source

Resync the generated Supported Actions tables to handler source after
rebasing onto the latest main:

- cloudformation: add DescribeStackInstance and DescribeStackSetOperation
  now emitted by the handler, and keep the implemented StackSet descriptions
- cloudtrail: add LookupEvents
- firehose: add UpdateDestination
- step-functions: add PublishStateMachineVersion, ListStateMachineVersions,
  DeleteStateMachineVersion
- register the cloudcontrol handler in deferred_handlers so the strict
  unregistered-handler gate passes (no standalone action table yet)

* fix(docs): prevent action-table generator from silently dropping actions

Address the latest review pass on the action-docs tooling:

- switch extraction now captures case arms whose labels wrap across lines
  (valid Java 14+ syntax). The capture group excludes only `{ } ;` boundaries,
  so it spans newlines between labels but stops at the arm's `->`. A wrapped
  arm was previously missed, and docs-check would stay green because the doc
  and the generated output agreed on the omission, defeating the whole
  drift-prevention guarantee.
- REST extraction skips Javadoc / inline comments between a verb annotation
  and the method signature; such a line otherwise reset the lookahead and
  dropped the action.
- parse_marker_block raises a descriptive error when a marker is not on its
  own line, instead of a bare "substring not found".
- doc, source, and registry reads/writes are pinned to UTF-8 so generation is
  locale-independent (the docs contain non-ASCII text).
- the docs-actions push trigger watches Makefile and the workflow file,
  matching its pull_request trigger.

Adds regression tests for the multi-line arm and comment-skip paths (20 total).
2026-07-06 21:02:04 -05:00

252 lines
8.4 KiB
Python

"""Tests for regen_action_docs.
Run with: pytest tools/docs -q (or: make docs-test)
"""
from __future__ import annotations
from pathlib import Path
import pytest
import regen_action_docs as r
# --------------------------------------------------------------------------- #
# Extraction: switch
# --------------------------------------------------------------------------- #
def test_extract_switch_single_label():
src = """
return switch (action) {
case "CreateSecret" -> handleCreate(req);
case "GetSecretValue" -> handleGet(req);
default -> error();
};
"""
assert r.extract_switch_actions(src) == ["CreateSecret", "GetSecretValue"]
def test_extract_switch_multi_label_arm():
# A single arm carrying several labels (real case: CloudFormation StackSets).
src = 'case "ListStackSets", "DescribeStackSet", "CreateStackSet" -> handleStackSets(req);'
assert r.extract_switch_actions(src) == [
"ListStackSets",
"DescribeStackSet",
"CreateStackSet",
]
def test_extract_switch_multiline_arm():
# Labels wrapped across lines (valid Java 14+ switch syntax) must all be captured,
# and the capture must stop at the arm's `->` rather than running into the next
# arm's `{ ... }` body. A miss here would be invisible: the doc and the regenerated
# output would agree on the omission and docs-check would stay green.
src = '''
return switch (action) {
case "CreateStackSet",
"DescribeStackSet",
"ListStackSets" -> handleStackSets(req);
case "GetTemplate" -> { return handleGet(req); }
};
'''
assert r.extract_switch_actions(src) == [
"CreateStackSet",
"DescribeStackSet",
"ListStackSets",
"GetTemplate",
]
def test_extract_switch_ignores_non_pascal_and_default():
src = '''
case "lowercase" -> a();
case null, default -> b();
case "Good" -> c();
'''
assert r.extract_switch_actions(src) == ["Good"]
def test_extract_switch_excludes_screaming_case_enum_labels():
# A handler may contain non-action switches (e.g. state enums). SCREAMING_CASE
# labels must not be picked up as actions; PascalCase actions still are.
src = '''
return switch (action) {
case "EnableRule" -> enable();
case "DisableRule" -> disable();
};
return switch (state.toUpperCase()) {
case "DISABLED" -> RuleState.DISABLED;
case "ENABLED" -> RuleState.ENABLED;
};
'''
assert r.extract_switch_actions(src) == ["EnableRule", "DisableRule"]
# --------------------------------------------------------------------------- #
# Extraction: rest + overrides
# --------------------------------------------------------------------------- #
REST_CONTROLLER = """
@Path("/")
public class ThingController {
@POST
public Response createThing(Req r) { return ok(); }
@GET
public Response listThingsPost(Req r) { return ok(); }
@PUT
public Response updateV2Thing(Req r) { return ok(); }
}
"""
def test_extract_rest_ucfirsts_method_names():
assert r.extract_rest_actions(REST_CONTROLLER) == [
"CreateThing",
"ListThingsPost",
"UpdateV2Thing",
]
def test_extract_rest_requires_class_path():
no_path = REST_CONTROLLER.replace('@Path("/")\n', "")
assert r.extract_rest_actions(no_path) == []
def test_extract_rest_skips_comments_between_annotation_and_method():
# A Javadoc or inline comment sitting between the verb annotation and the method
# signature must not reset the lookahead and drop the action.
src = '''
@Path("/")
public class C {
@POST
/** Creates a thing. */
public Response createThing(Req r) { return ok(); }
@GET
// list them
public Response listThings(Req r) { return ok(); }
}
'''
assert r.extract_rest_actions(src) == ["CreateThing", "ListThings"]
def test_extract_actions_applies_rename_and_exclude(tmp_path: Path):
src = tmp_path / "ThingController.java"
src.write_text(REST_CONTROLLER)
entry = r.ServiceEntry(
service="thing",
doc=tmp_path / "thing.md",
sources=[r.Source(path=src, mode="rest")],
rename_actions={"UpdateV2Thing": "UpdateThing"},
exclude_actions=frozenset({"ListThingsPost"}),
)
assert r.extract_actions(entry) == ["CreateThing", "UpdateThing"]
def test_extract_actions_dedupes_across_sources(tmp_path: Path):
a = tmp_path / "A.java"
b = tmp_path / "B.java"
a.write_text('case "Foo" -> x();\ncase "Bar" -> y();')
b.write_text('case "Bar" -> y();\ncase "Baz" -> z();')
entry = r.ServiceEntry(
service="s",
doc=tmp_path / "s.md",
sources=[r.Source(path=a, mode="switch"), r.Source(path=b, mode="switch")],
)
assert r.extract_actions(entry) == ["Foo", "Bar", "Baz"]
# --------------------------------------------------------------------------- #
# Table parsing: robustness
# --------------------------------------------------------------------------- #
def test_split_row_honors_escaped_pipe():
assert r._split_row(r"| `Foo` | a \| b |") == ["`Foo`", "a | b"]
def test_parse_marker_block_preserves_descriptions():
md = (
"pre\n"
f"{r.MARKER_START}\n"
"| Action | Description |\n"
"| --- | --- |\n"
"| `CreateSecret` | Create a new secret |\n"
"| `GetSecretValue` | - |\n"
f"{r.MARKER_END}\n"
"post\n"
)
_, descs, _ = r.parse_marker_block(md)
assert descs == {"CreateSecret": "Create a new secret", "GetSecretValue": ""}
def test_parse_marker_block_rejects_missing_markers():
with pytest.raises(ValueError):
r.parse_marker_block("no markers here")
def test_parse_table_rejects_non_table_line():
body = "| Action | Description |\n| --- | --- |\nstray prose line\n"
with pytest.raises(ValueError):
r._parse_table(body)
def test_parse_table_rejects_extra_columns():
# An unescaped pipe in a hand-edited description yields a 3-cell row; reject it
# loudly rather than silently dropping the trailing text.
body = "| Action | Description |\n| --- | --- |\n| `Foo` | a | b |\n"
with pytest.raises(ValueError):
r._parse_table(body)
def test_pipe_in_description_round_trips():
# A description containing a literal pipe survives render -> parse -> render
# unchanged (render escapes, the parser unescapes), and stays idempotent.
block = r.render_marker_block(["Foo"], {"Foo": "does a | b"})
assert r"\|" in block # escaped on render
md = f"x\n{r.MARKER_START}\n{block}{r.MARKER_END}\n"
_, descs, _ = r.parse_marker_block(md)
assert descs["Foo"] == "does a | b" # unescaped on parse
assert r.render_marker_block(["Foo"], descs) == block # idempotent
# --------------------------------------------------------------------------- #
# Regeneration: preservation, placeholders, orphans, idempotency
# --------------------------------------------------------------------------- #
DOC = (
"# Svc\n\n## Supported Actions\n\n"
f"{r.MARKER_START}\n"
"| Action | Description |\n"
"| --- | --- |\n"
"| `CreateSecret` | Create a new secret |\n"
"| `OldAction` | gone from code |\n"
f"{r.MARKER_END}\n\n## Configuration\nprose\n"
)
def test_regenerate_preserves_known_and_placeholders_new():
actions = ["CreateSecret", "GetSecretValue"]
new, orphans = r.regenerate_doc_content(actions, DOC)
_, descs, _ = r.parse_marker_block(new)
assert descs["CreateSecret"] == "Create a new secret" # preserved
assert descs["GetSecretValue"] == "" # new -> placeholder
assert orphans == ["OldAction"] # dropped + reported
assert "OldAction" not in new
def test_regenerate_is_idempotent():
actions = ["CreateSecret", "GetSecretValue"]
once, _ = r.regenerate_doc_content(actions, DOC)
twice, _ = r.regenerate_doc_content(actions, once)
assert once == twice
def test_regenerate_touches_only_marker_block():
actions = ["CreateSecret", "GetSecretValue"]
new, _ = r.regenerate_doc_content(actions, DOC)
assert new.split(r.MARKER_START)[0] == DOC.split(r.MARKER_START)[0]
assert new.split(r.MARKER_END)[1] == DOC.split(r.MARKER_END)[1]
def test_render_marker_block_shape():
out = r.render_marker_block(["Foo"], {"Foo": "does foo"})
assert out == "| Action | Description |\n| --- | --- |\n| `Foo` | does foo |\n"