Light, fluffy, and always free - The AWS Local Emulator alternative
docs(cloudformation): generate the supported resource-type table (#2739)
Hector Venturab76eadc98eb1
diff --git a/.github/workflows/docs-actions.yml b/.github/workflows/docs-actions.ymlindex 4e49840778..2484b20784 100644--- a/.github/workflows/docs-actions.yml+++ b/.github/workflows/docs-actions.yml@@ -1,13 +1,16 @@name: Docs Action Tables-# Keeps the generated "Supported Actions" tables in docs/services/*.md in sync with-# handler source. Runs on handler changes (which can add/remove actions) and on doc or-# tooling changes. Python-only, so it is fast and independent of the Java build job.+# Keeps the generated tables in docs/services/*.md in sync with their sources: the+# "Supported Actions" tables with handler source, and the CloudFormation "Supported Resource+# Types" table with the provisioner inventory TSV. Runs on handler changes (which can add or+# remove actions), inventory changes (which add or move resource types), and on doc or tooling+# changes. Python-only, so it is fast and independent of the Java build job.on:pull_request:paths:- 'src/main/**'+ - 'src/test/resources/cloudformation/**'- 'docs/services/**'- 'tools/docs/**'- 'Makefile'@@ -17,6 +20,7 @@ on:- mainpaths:- 'src/main/**'+ - 'src/test/resources/cloudformation/**'- 'docs/services/**'- 'tools/docs/**'- 'Makefile'diff --git a/Makefile b/Makefileindex 5081a73142..c05c3a56f6 100644--- a/Makefile+++ b/Makefile@@ -12,6 +12,7 @@ PYTHON ?= python3docs-sync: ## Regenerate the action tables in docs/services from handler source (in place)$(PYTHON) tools/docs/regen_action_docs.py+ $(PYTHON) tools/docs/regen_cfn_resource_types.pydocs-check: ## CI gate: regenerate and fail if anything is stale, unregistered, or undocumented@$(PYTHON) tools/docs/regen_action_docs.py --strict || { \@@ -19,6 +20,12 @@ docs-check: ## CI gate: regenerate and fail if anything is stale, unregistered,echo "error: action-table regeneration reported problems (see warnings above)."; \exit 1; \}+ @$(PYTHON) tools/docs/regen_cfn_resource_types.py --strict || { \+ echo ""; \+ echo "error: the CloudFormation resource-type table is stale or reported problems."; \+ echo " Run 'make docs-sync' and commit the result."; \+ exit 1; \+ }@git diff --exit-code -- docs/ || { \echo ""; \echo "error: docs/services action tables are out of date."; \diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 626c4555a7..4b994fb1bf 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -49,31 +49,32 @@ the backing service and sets a real physical ID plus the `Ref` / `Fn::GetAtt` atcross-resource references.> Adding a type? See [Adding a CloudFormation Resource Type](../../CONTRIBUTING.md#adding-a-cloudformation-resource-type).-> Types live in per-service provisioners under `services/cloudformation/provisioners/`; keep this-> table in step with them.+> Types live in per-service provisioners under `services/cloudformation/provisioners/`. This table+> is generated from the provisioner inventory by `make docs-sync`; edit that, not the table.+<!-- floci:cfn-types:start -->| Service | Resource types ||---|---|| S3 | `Bucket`, `BucketPolicy` (accepted; policy not enforced) || SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) || SNS | `Topic`, `Subscription` || DynamoDB | `Table`, `GlobalTable` |-| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work |+| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `MicrovmImage`, `NetworkConnector`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. || IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` || Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` || SSM | `Parameter` || KMS | `Key`, `Alias` || Secrets Manager | `Secret`, `SecretTargetAttachment` || ECR | `Repository` |-| ECS | `Cluster`, `TaskDefinition`, `Service` |+| ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` || EKS | `Cluster`, `Nodegroup` |-| RDS | `DBInstance`, `DBCluster`, `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup` (DBInstance/DBCluster start real containers) |-| EC2 | `VPC`, `Subnet`, `SecurityGroup` (including inline `SecurityGroupIngress`/`SecurityGroupEgress`), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |+| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |+| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` || Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` || Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook` || Route 53 | `HostedZone`, `RecordSet` || API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account` |-| API Gateway v2 | `Api`, `Route`, `Integration`, `Stage`, `Deployment` |+| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` || Step Functions | `StateMachine` || CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` || CodeBuild | `Project` |@@ -83,12 +84,14 @@ cross-resource references.| Pipes | `Pipe` || Kinesis | `Stream` || Kinesis Data Firehose | `DeliveryStream` |+| CloudFront | `Distribution` || CloudWatch | `Alarm` || CloudWatch Logs | `LogGroup` || WAFv2 | `WebACL` || Config | `ConfigRule` |-| CloudFormation | `Stack` (nested stacks), `CustomResource` and `Custom::*` (Lambda-backed) |+| CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) || CDK | `CDK::Metadata` (accepted; no-op) |+<!-- floci:cfn-types:end -->All other resource types are accepted without error and assigned a synthetic physical ID (with an`arn:aws:stub:::<logicalId>` ARN attribute), so templates with unsupported types still reachdiff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yamlnew file mode 100644index 0000000000..1bc083f439--- /dev/null+++ b/tools/docs/cfn_resource_types.yaml@@ -0,0 +1,165 @@+# Presentation for the generated "Supported Resource Types" table in+# docs/services/cloudformation.md. The set of types is NOT configured here: it comes from+# src/test/resources/cloudformation/supported-resource-types.tsv, which CfnResourceInventoryTest+# pins to the CDI-resolved provisioner registry and the legacy switch. This file only decides how+# those types are labelled, ordered and annotated.+#+# Adding a resource type: add the provisioner, update the TSV, run `make docs-sync`. Touch this+# file only for a new namespace (which needs a label) or to add a note.++# Row order. Namespaces omitted here are appended alphabetically after these, so a forgotten+# entry degrades to a sensible position rather than disappearing.+order:+ - AWS::S3+ - AWS::SQS+ - AWS::SNS+ - AWS::DynamoDB+ - AWS::Lambda+ - AWS::IAM+ - AWS::Organizations+ - AWS::SSM+ - AWS::KMS+ - AWS::SecretsManager+ - AWS::ECR+ - AWS::ECS+ - AWS::EKS+ - AWS::RDS+ - AWS::EC2+ - AWS::ElasticLoadBalancingV2+ - AWS::AutoScaling+ - AWS::Route53+ - AWS::ApiGateway+ - AWS::ApiGatewayV2+ - AWS::StepFunctions+ - AWS::CodePipeline+ - AWS::CodeBuild+ - AWS::Batch+ - AWS::Cognito+ - AWS::Events+ - AWS::Pipes+ - AWS::Kinesis+ - AWS::KinesisFirehose+ - AWS::CloudFront+ - AWS::CloudWatch+ - AWS::Logs+ - AWS::WAFv2+ - AWS::Config+ - AWS::CloudFormation+ - Custom+ - AWS::CDK++# Namespaces folded into another row. Custom::* types are CloudFormation's own extension+# mechanism, not a service of their own, so they belong in the CloudFormation row.+merge_namespaces:+ Custom: AWS::CloudFormation++# Overrides the name shown for a type. Only needed where the bare leaf would be ambiguous.+display_names:+ AWS::CDK::Metadata: CDK::Metadata++# Order of type names within a row. Listed names come first in this order; anything else is+# appended alphabetically, so a newly provisioned type appears without needing an entry here.+# Curated where the reading order carries meaning (primary resources before their accessories).+type_order:+ AWS::S3: [Bucket, BucketPolicy]+ AWS::SQS: [Queue, QueuePolicy]+ AWS::SNS: [Topic, Subscription]+ AWS::DynamoDB: [Table, GlobalTable]+ AWS::Lambda: [Function, LayerVersion, EventSourceMapping, Version, Alias, Permission]+ AWS::IAM: [Role, User, AccessKey, Policy, ManagedPolicy, InstanceProfile]+ AWS::Organizations: [Organization, OrganizationalUnit, Account, Policy, ResourcePolicy]+ AWS::KMS: [Key, Alias]+ AWS::SecretsManager: [Secret, SecretTargetAttachment]+ AWS::ECS: [Cluster, TaskDefinition, Service]+ AWS::EKS: [Cluster, Nodegroup]+ AWS::RDS:+ [DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup]+ AWS::EC2:+ [VPC, Subnet, SecurityGroup, SecurityGroupIngress, SecurityGroupEgress, InternetGateway,+ RouteTable, SubnetRouteTableAssociation, Route, NatGateway, EIP, Instance, LaunchTemplate,+ VPCGatewayAttachment, VPCEndpoint, NetworkAcl, NetworkAclEntry, SubnetNetworkAclAssociation,+ FlowLog]+ AWS::ElasticLoadBalancingV2: [LoadBalancer, TargetGroup, Listener, ListenerRule]+ AWS::AutoScaling: [LaunchConfiguration, AutoScalingGroup, LifecycleHook]+ AWS::Route53: [HostedZone, RecordSet]+ AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account]+ AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment]+ AWS::CodePipeline: [Pipeline, CustomActionType, Webhook]+ AWS::Batch: [ComputeEnvironment, JobQueue, JobDefinition]+ AWS::Cognito: [UserPool, UserPoolClient]+ AWS::Events: [Rule, EventBus, EventBusPolicy]+ AWS::CloudFormation: [CustomResource]++# Namespace -> the service name shown in the Service column.+service_labels:+ AWS::ApiGateway: API Gateway (v1)+ AWS::ApiGatewayV2: API Gateway v2+ AWS::AutoScaling: Auto Scaling+ AWS::Batch: Batch+ AWS::CDK: CDK+ AWS::CloudFormation: CloudFormation+ AWS::CloudFront: CloudFront+ AWS::CloudWatch: CloudWatch+ AWS::CodeBuild: CodeBuild+ AWS::CodePipeline: CodePipeline+ AWS::Cognito: Cognito+ AWS::Config: Config+ AWS::DynamoDB: DynamoDB+ AWS::EC2: EC2+ AWS::ECR: ECR+ AWS::ECS: ECS+ AWS::EKS: EKS+ AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2+ AWS::Events: EventBridge+ AWS::IAM: IAM+ AWS::KMS: KMS+ AWS::Kinesis: Kinesis+ AWS::KinesisFirehose: Kinesis Data Firehose+ AWS::Lambda: Lambda+ AWS::Logs: CloudWatch Logs+ AWS::Organizations: Organizations+ AWS::Pipes: Pipes+ AWS::RDS: RDS+ AWS::Route53: Route 53+ AWS::S3: S3+ AWS::SNS: SNS+ AWS::SQS: SQS+ AWS::SSM: SSM+ AWS::SecretsManager: Secrets Manager+ AWS::StepFunctions: Step Functions+ AWS::WAFv2: WAFv2+ Custom: CloudFormation++# Parenthetical shown after a type name. Keyed by the full type.+notes:+ AWS::S3::BucketPolicy: accepted; policy not enforced+ AWS::SQS::QueuePolicy: accepted; policy not enforced+ AWS::Lambda::Function: Zip via S3/inline `ZipFile`, and Image+ AWS::Lambda::EventSourceMapping: SQS, Kinesis, DynamoDB Streams+ AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands into+ AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported+ AWS::RDS::DBInstance: starts a real container+ AWS::RDS::DBCluster: starts a real container+ AWS::CDK::Metadata: accepted; no-op+ Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda++# Trailing prose appended to a row after its type list, for behaviour that belongs to the service+# rather than to one type.+row_notes:+ AWS::Lambda: >-+ Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module+ AWS injects for that code path, so Solutions-style custom-resource handlers work.++# Capabilities that belong in this table but are not provisioner types, so they cannot come from+# the inventory. Each needs a reason, because an entry here is exempt from the drift check.+extra_types:+ AWS::CloudFormation:+ - name: Stack+ note: nested stacks+ reason: >-+ Handled by CloudFormationService as a child-stack lifecycle, not by a resource provisioner.+ - name: Custom::*+ note: Lambda-backed+ reason: >-+ A wildcard prefix, not an exact type. The registry is keyed by exact type, so this is+ dispatched by a prefix branch and can never appear in the inventory.diff --git a/tools/docs/regen_cfn_resource_types.py b/tools/docs/regen_cfn_resource_types.pynew file mode 100644index 0000000000..7b760df479--- /dev/null+++ b/tools/docs/regen_cfn_resource_types.py@@ -0,0 +1,219 @@+#!/usr/bin/env python3+"""Regenerate the "Supported Resource Types" table in docs/services/cloudformation.md.++The set of types comes from src/test/resources/cloudformation/supported-resource-types.tsv,+which CfnResourceInventoryTest pins to the CDI-resolved provisioner registry plus the legacy+switch. Presentation (row order, service labels, notes) comes from cfn_resource_types.yaml.++Deliberately reads the TSV rather than parsing the Java: several provisioners return+`Set.of(CONSTANT, CONSTANT)` from resourceTypes(), so a source regex sees only a subset. The+TSV is the one representation that is both machine-checked against the running registry and+readable without a JVM.++ python3 tools/docs/regen_cfn_resource_types.py # rewrite in place+ python3 tools/docs/regen_cfn_resource_types.py --check # exit 1 if stale+ python3 tools/docs/regen_cfn_resource_types.py --strict # also fail on warnings+"""++from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path++import yaml++REPO_ROOT = Path(__file__).resolve().parents[2]+INVENTORY = REPO_ROOT / "src/test/resources/cloudformation/supported-resource-types.tsv"+CONFIG = Path(__file__).resolve().parent / "cfn_resource_types.yaml"+DOC = REPO_ROOT / "docs/services/cloudformation.md"+PROVISIONER_DIR = REPO_ROOT / "src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners"++MARKER_START = "<!-- floci:cfn-types:start -->"+MARKER_END = "<!-- floci:cfn-types:end -->"+++def load_inventory(path: Path = INVENTORY) -> list[tuple[str, str]]:+ """[(resource_type, owner)] in file order."""+ rows = []+ for line in path.read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ parts = line.split("\t")+ if len(parts) != 2:+ raise ValueError(f"{path.name}: expected 'type<TAB>owner', got: {line!r}")+ rows.append((parts[0], parts[1]))+ return rows+++def namespace_of(resource_type: str) -> str:+ """AWS::SQS::Queue -> AWS::SQS; Custom::DynamoDBReplica -> Custom."""+ parts = resource_type.split("::")+ return "::".join(parts[:2]) if len(parts) == 3 else parts[0]+++def leaf_of(resource_type: str) -> str:+ """AWS::SQS::Queue -> Queue; Custom::DynamoDBReplica -> Custom::DynamoDBReplica.++ A two-segment type has no namespace to strip, so it is shown whole; abbreviating+ Custom::DynamoDBReplica to DynamoDBReplica would read as an AWS type that does not exist.+ """+ parts = resource_type.split("::")+ return parts[2] if len(parts) == 3 else resource_type+++def render_rows(inventory, config) -> tuple[list[str], list[str]]:+ """Returns (table_lines, warnings)."""+ warnings: list[str] = []+ labels = config.get("service_labels", {}) or {}+ notes = config.get("notes", {}) or {}+ row_notes = config.get("row_notes", {}) or {}+ extras = config.get("extra_types", {}) or {}+ order = config.get("order", []) or []++ merges = config.get("merge_namespaces", {}) or {}+ displays = config.get("display_names", {}) or {}+ type_order = config.get("type_order", {}) or {}++ by_namespace: dict[str, list[str]] = {}+ for resource_type, _owner in inventory:+ ns = namespace_of(resource_type)+ by_namespace.setdefault(merges.get(ns, ns), []).append(resource_type)++ # Curated order first (it reads by importance, not alphabet), then anything new+ # alphabetically so a type added without touching this config still lands somewhere sane.+ for ns, types in by_namespace.items():+ wanted = type_order.get(ns, [])+ rank = {name: i for i, name in enumerate(wanted)}+ types.sort(key=lambda t: (rank.get(leaf_of(t), len(rank)), leaf_of(t)))+ for leaf in wanted:+ if leaf not in {leaf_of(t) for t in types}:+ warnings.append(+ f"type_order for {ns} lists {leaf}, which nothing provisions; "+ f"remove it or fix the spelling"+ )++ namespaces = list(by_namespace) + [ns for ns in extras if ns not in by_namespace]+ ranked = [ns for ns in order if ns in namespaces]+ ranked += sorted(ns for ns in namespaces if ns not in order)++ for ns in namespaces:+ if ns not in labels:+ warnings.append(+ f"no service_labels entry for {ns}; add one to cfn_resource_types.yaml "+ f"so the row gets a readable service name"+ )+ if ns not in order:+ warnings.append(f"{ns} is not in the order list; appended alphabetically")++ lines = ["| Service | Resource types |", "|---|---|"]+ for ns in ranked:+ cells = []+ for resource_type in by_namespace.get(ns, []):+ note = notes.get(resource_type)+ shown = displays.get(resource_type, leaf_of(resource_type))+ cells.append(f"`{shown}`" + (f" ({note})" if note else ""))+ for extra in extras.get(ns, []):+ if not extra.get("reason"):+ warnings.append(+ f"extra_types entry {ns} / {extra.get('name')} has no reason; "+ f"an entry exempt from the inventory check must say why"+ )+ note = extra.get("note")+ cells.append(f"`{extra['name']}`" + (f" ({note})" if note else ""))+ if not cells:+ continue+ types = ", ".join(cells)+ trailing = (row_notes.get(ns) or "").strip()+ if trailing:+ types = f"{types}. {trailing}"+ lines.append(f"| {labels.get(ns, ns)} | {types} |")+ return lines, warnings+++def check_provisioner_annotations() -> list[str]:+ """A CfnResourceProvisioner without @ApplicationScoped is never discovered by CDI.++ CfnResourceInventoryTest catches this at runtime; flagging it here too means the cheap+ check runs in docs-check, before anyone waits on a Quarkus test boot.+ """+ warnings = []+ if not PROVISIONER_DIR.is_dir():+ return warnings+ for path in sorted(PROVISIONER_DIR.glob("*CfnProvisioner.java")):+ src = path.read_text(encoding="utf-8")+ if "implements CfnResourceProvisioner" not in src:+ continue+ if "@ApplicationScoped" not in src:+ warnings.append(+ f"{path.name} implements CfnResourceProvisioner without @ApplicationScoped, "+ f"so CDI never registers it and its types are silently stubbed"+ )+ return warnings+++def check_no_double_ownership(inventory) -> list[str]:+ """A type served by a provisioner must not also sit in the legacy switch."""+ owners: dict[str, set[str]] = {}+ for resource_type, owner in inventory:+ owners.setdefault(resource_type, set()).add(owner)+ return [+ f"{resource_type} is claimed by both the legacy switch and {sorted(o - {'LEGACY_SWITCH'})[0]}; "+ f"the registry wins, leaving the switch arm as dead code"+ for resource_type, o in sorted(owners.items())+ if len(o) > 1 and "LEGACY_SWITCH" in o+ ]+++def splice(md: str, table: list[str]) -> str:+ if md.count(MARKER_START) != 1 or md.count(MARKER_END) != 1:+ raise ValueError(+ f"{DOC.name} must contain exactly one {MARKER_START} and one {MARKER_END}"+ )+ start, end = md.index(MARKER_START), md.index(MARKER_END)+ if end < start:+ raise ValueError("end marker appears before start marker")+ after_start = md.index("\n", start) + 1+ before_end = md.rindex("\n", 0, end) + 1+ return md[:after_start] + "\n".join(table) + "\n" + md[before_end:]+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true", help="exit 1 if the doc is stale")+ parser.add_argument("--strict", action="store_true", help="also exit 1 on warnings")+ args = parser.parse_args(argv)++ inventory = load_inventory()+ config = yaml.safe_load(CONFIG.read_text(encoding="utf-8")) or {}+ table, warnings = render_rows(inventory, config)+ warnings += check_no_double_ownership(inventory)+ warnings += check_provisioner_annotations()++ for warning in warnings:+ print(f"warning: {warning}", file=sys.stderr)++ current = DOC.read_text(encoding="utf-8")+ updated = splice(current, table)+ stale = updated != current++ if args.check or args.strict:+ if stale:+ print(+ f"error: {DOC.relative_to(REPO_ROOT)} resource-type table is stale. "+ f"Run 'make docs-sync' and commit the result.",+ file=sys.stderr,+ )+ return 1 if (stale or (args.strict and warnings)) else 0++ if stale:+ DOC.write_text(updated, encoding="utf-8")+ print(f"updated {DOC.relative_to(REPO_ROOT)} ({len(table) - 2} rows)")+ else:+ print(f"{DOC.relative_to(REPO_ROOT)} already up to date ({len(table) - 2} rows)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tools/docs/test_regen_cfn_resource_types.py b/tools/docs/test_regen_cfn_resource_types.pynew file mode 100644index 0000000000..d8e55b9b68--- /dev/null+++ b/tools/docs/test_regen_cfn_resource_types.py@@ -0,0 +1,167 @@+"""Tests for regen_cfn_resource_types.++Run with: pytest tools/docs -q (or: make docs-test)+"""+from __future__ import annotations++import pytest++import regen_cfn_resource_types as r+++BASE_CONFIG = {+ "order": ["AWS::S3", "AWS::CloudFormation"],+ "service_labels": {+ "AWS::S3": "S3",+ "AWS::CloudFormation": "CloudFormation",+ "AWS::SQS": "SQS",+ },+}+++def render(inventory, **overrides):+ config = {**BASE_CONFIG, **overrides}+ return r.render_rows(inventory, config)+++# --------------------------------------------------------------------------- #+# Type naming+# --------------------------------------------------------------------------- #+def test_namespace_and_leaf_of_a_three_segment_type():+ assert r.namespace_of("AWS::SQS::Queue") == "AWS::SQS"+ assert r.leaf_of("AWS::SQS::Queue") == "Queue"+++def test_two_segment_type_keeps_its_prefix():+ # Abbreviating Custom::DynamoDBReplica to DynamoDBReplica would read as an AWS+ # resource type that does not exist.+ assert r.namespace_of("Custom::DynamoDBReplica") == "Custom"+ assert r.leaf_of("Custom::DynamoDBReplica") == "Custom::DynamoDBReplica"+++# --------------------------------------------------------------------------- #+# Rendering+# --------------------------------------------------------------------------- #+def test_renders_one_row_per_namespace_in_configured_order():+ lines, warnings = render(+ [("AWS::SQS::Queue", "SqsCfnProvisioner"), ("AWS::S3::Bucket", "LEGACY_SWITCH")]+ )+ assert lines[0] == "| Service | Resource types |"+ # S3 is in the order list, SQS is not, so SQS is appended after it.+ assert lines[2] == "| S3 | `Bucket` |"+ assert lines[3] == "| SQS | `Queue` |"+ assert any("not in the order list" in w for w in warnings)+++def test_unlisted_types_sort_alphabetically_after_curated_ones():+ inventory = [+ ("AWS::S3::AccessPoint", "LEGACY_SWITCH"),+ ("AWS::S3::Bucket", "LEGACY_SWITCH"),+ ("AWS::S3::BucketPolicy", "LEGACY_SWITCH"),+ ]+ lines, _ = render(inventory, type_order={"AWS::S3": ["Bucket", "BucketPolicy"]})+ assert lines[2] == "| S3 | `Bucket`, `BucketPolicy`, `AccessPoint` |"+++def test_notes_and_row_notes_are_appended():+ lines, _ = render(+ [("AWS::S3::Bucket", "LEGACY_SWITCH")],+ notes={"AWS::S3::Bucket": "accepted; policy not enforced"},+ row_notes={"AWS::S3": "Trailing prose."},+ )+ assert lines[2] == "| S3 | `Bucket` (accepted; policy not enforced). Trailing prose. |"+++def test_display_names_override_the_leaf():+ lines, _ = render(+ [("AWS::CDK::Metadata", "LEGACY_SWITCH")],+ service_labels={**BASE_CONFIG["service_labels"], "AWS::CDK": "CDK"},+ display_names={"AWS::CDK::Metadata": "CDK::Metadata"},+ )+ assert "`CDK::Metadata`" in lines[2]+++def test_merged_namespace_folds_into_one_row():+ lines, _ = render(+ [+ ("AWS::CloudFormation::CustomResource", "LEGACY_SWITCH"),+ ("Custom::DynamoDBReplica", "LEGACY_SWITCH"),+ ],+ merge_namespaces={"Custom": "AWS::CloudFormation"},+ )+ rows = [line for line in lines if line.startswith("| CloudFormation ")]+ assert len(rows) == 1, "Custom::* belongs in the CloudFormation row, not a second one"+ assert "`Custom::DynamoDBReplica`" in rows[0]+++def test_extra_types_appear_after_inventory_types():+ lines, _ = render(+ [("AWS::CloudFormation::CustomResource", "LEGACY_SWITCH")],+ extra_types={+ "AWS::CloudFormation": [+ {"name": "Stack", "note": "nested stacks", "reason": "not a provisioner type"}+ ]+ },+ )+ assert lines[2] == "| CloudFormation | `CustomResource`, `Stack` (nested stacks) |"+++# --------------------------------------------------------------------------- #+# Warnings: these are the drift the gate exists to catch+# --------------------------------------------------------------------------- #+def test_warns_when_a_namespace_has_no_label():+ _, warnings = render([("AWS::Athena::WorkGroup", "AthenaCfnProvisioner")])+ assert any("no service_labels entry for AWS::Athena" in w for w in warnings)+++def test_warns_when_type_order_names_a_type_nothing_provisions():+ _, warnings = render(+ [("AWS::S3::Bucket", "LEGACY_SWITCH")],+ type_order={"AWS::S3": ["Bucket", "Buckett"]},+ )+ assert any("lists Buckett" in w for w in warnings)+++def test_warns_when_an_extra_type_has_no_reason():+ _, warnings = render(+ [("AWS::CloudFormation::CustomResource", "LEGACY_SWITCH")],+ extra_types={"AWS::CloudFormation": [{"name": "Stack"}]},+ )+ assert any("has no reason" in w for w in warnings)+++def test_warns_when_a_type_is_claimed_by_both_the_switch_and_a_provisioner():+ # The registry wins, so the switch arm is dead code that still looks live.+ warnings = r.check_no_double_ownership(+ [("AWS::SQS::Queue", "LEGACY_SWITCH"), ("AWS::SQS::Queue", "SqsCfnProvisioner")]+ )+ assert len(warnings) == 1+ assert "SqsCfnProvisioner" in warnings[0]+++def test_no_double_ownership_warning_when_each_type_has_one_owner():+ assert r.check_no_double_ownership(+ [("AWS::SQS::Queue", "SqsCfnProvisioner"), ("AWS::S3::Bucket", "LEGACY_SWITCH")]+ ) == []+++# --------------------------------------------------------------------------- #+# Inventory parsing and splicing+# --------------------------------------------------------------------------- #+def test_load_inventory_rejects_a_malformed_row(tmp_path):+ path = tmp_path / "inv.tsv"+ path.write_text("AWS::SQS::Queue\tSqsCfnProvisioner\nAWS::S3::Bucket\n", encoding="utf-8")+ with pytest.raises(ValueError, match="expected 'type<TAB>owner'"):+ r.load_inventory(path)+++def test_splice_replaces_only_the_marked_block():+ md = f"before\n{r.MARKER_START}\nold table\n{r.MARKER_END}\nafter\n"+ assert r.splice(md, ["new table"]) == (+ f"before\n{r.MARKER_START}\nnew table\n{r.MARKER_END}\nafter\n"+ )+++def test_splice_requires_exactly_one_marker_pair():+ with pytest.raises(ValueError, match="exactly one"):+ r.splice("no markers here\n", ["x"])