Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

chore(tools): generate the request shapes from one shared script (#5816)

Kenshin Okinaka6aac097c82a3
diff --git a/tools/aws/regen_dynamodb_shapes.py b/tools/aws/regen_dynamodb_shapes.py
index 83f6fc1a47..de83694a46 100644
--- a/tools/aws/regen_dynamodb_shapes.py
+++ b/tools/aws/regen_dynamodb_shapes.py
@@ -18,92 +18,17 @@ Run from anywhere in the repo:
"""
from __future__ import annotations
-import argparse
-import gzip
-import json
import sys
from pathlib import Path
-from regen_partitions import resolve_botocore_data, strip_source
+import request_shapes
-REPO_ROOT = Path(__file__).resolve().parents[2]
-OUTPUT = REPO_ROOT / "src/main/resources/aws/dynamodb-request-shapes.json"
-MODEL = Path("dynamodb/2012-08-10/service-2.json")
-
-
-def load_model(data: Path, model: Path = MODEL) -> dict:
- plain = data / model
- if plain.exists():
- return json.loads(plain.read_text(encoding="utf-8"))
- compressed = plain.with_name(plain.name + ".gz")
- if compressed.exists():
- with gzip.open(compressed, "rt", encoding="utf-8") as f:
- return json.load(f)
- raise SystemExit(f"error: {plain} not found")
-
-
-def build(model: dict, provenance: str) -> dict:
- shapes = model["shapes"]
- kept: dict[str, dict] = {}
-
- def keep(name: str) -> None:
- if name in kept:
- return
- shape = shapes[name]
- kind = shape["type"]
- entry: dict = {"type": kind}
- kept[name] = entry
- if kind == "structure":
- entry["members"] = {member: spec["shape"] for member, spec in shape.get("members", {}).items()}
- for spec in shape.get("members", {}).values():
- keep(spec["shape"])
- elif kind == "list":
- entry["member"] = shape["member"]["shape"]
- keep(shape["member"]["shape"])
- elif kind == "map":
- entry["value"] = shape["value"]["shape"]
- keep(shape["value"]["shape"])
-
- operations = {}
- for name, operation in sorted(model["operations"].items()):
- if "input" in operation:
- operations[name] = operation["input"]["shape"]
- keep(operation["input"]["shape"])
-
- return {
- "_source": {
- "generator": "tools/aws/regen_dynamodb_shapes.py",
- "botocore": provenance,
- },
- "operations": operations,
- "shapes": dict(sorted(kept.items())),
- }
-
-
-def render(doc: dict) -> str:
- return json.dumps(doc, indent=2, sort_keys=False) + "\n"
+OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/dynamodb-request-shapes.json"
+MODEL = Path("dynamodb/2012-08-10")
def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
- parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
- parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
- args = parser.parse_args(argv)
-
- data, provenance = resolve_botocore_data(args.botocore_data)
- fresh = render(build(load_model(data), provenance))
-
- if args.check:
- current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
- if strip_source(current) != strip_source(fresh):
- print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
- return 1
- return 0
-
- args.output.write_text(fresh, encoding="utf-8")
- print(f"wrote {args.output.relative_to(REPO_ROOT)} from {provenance}")
- return 0
+ return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__)
if __name__ == "__main__":
diff --git a/tools/aws/regen_sesv2_shapes.py b/tools/aws/regen_sesv2_shapes.py
index 5246a35970..939e59cab8 100644
--- a/tools/aws/regen_sesv2_shapes.py
+++ b/tools/aws/regen_sesv2_shapes.py
@@ -22,78 +22,17 @@ Run from anywhere in the repo:
"""
from __future__ import annotations
-import argparse
import sys
from pathlib import Path
-from regen_dynamodb_shapes import load_model, render
-from regen_partitions import resolve_botocore_data, strip_source
+import request_shapes
-REPO_ROOT = Path(__file__).resolve().parents[2]
-OUTPUT = REPO_ROOT / "src/main/resources/aws/sesv2-request-shapes.json"
-MODEL = Path("sesv2/2019-09-27/service-2.json")
-
-
-def build(model: dict, provenance: str) -> dict:
- shapes = model["shapes"]
- kept: dict[str, dict] = {}
-
- def keep(name: str, body_only: bool = False) -> None:
- if name in kept:
- return
- shape = shapes[name]
- kind = shape["type"]
- entry: dict = {"type": kind}
- kept[name] = entry
- if kind == "structure":
- members = {member: spec for member, spec in shape.get("members", {}).items()
- if not (body_only and "location" in spec)}
- entry["members"] = {member: spec["shape"] for member, spec in members.items()}
- for spec in members.values():
- keep(spec["shape"])
- elif kind == "list":
- entry["member"] = shape["member"]["shape"]
- keep(shape["member"]["shape"])
- elif kind == "map":
- entry["value"] = shape["value"]["shape"]
- keep(shape["value"]["shape"])
-
- operations = {}
- for name, operation in sorted(model["operations"].items()):
- if "input" in operation:
- operations[name] = operation["input"]["shape"]
- keep(operation["input"]["shape"], body_only=True)
-
- return {
- "_source": {
- "generator": "tools/aws/regen_sesv2_shapes.py",
- "botocore": provenance,
- },
- "operations": operations,
- "shapes": dict(sorted(kept.items())),
- }
+OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/sesv2-request-shapes.json"
+MODEL = Path("sesv2/2019-09-27")
def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
- parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
- parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
- args = parser.parse_args(argv)
-
- data, provenance = resolve_botocore_data(args.botocore_data)
- fresh = render(build(load_model(data, MODEL), provenance))
-
- if args.check:
- current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
- if strip_source(current) != strip_source(fresh):
- print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
- return 1
- return 0
-
- args.output.write_text(fresh, encoding="utf-8")
- print(f"wrote {args.output.relative_to(REPO_ROOT)} from {provenance}")
- return 0
+ return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__)
if __name__ == "__main__":
diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py
new file mode 100644
index 0000000000..97a6a134ba
--- /dev/null
+++ b/tools/aws/request_shapes.py
@@ -0,0 +1,103 @@
+"""Shared generator for the vendored request shapes a service's request check reads.
+
+`regen_dynamodb_shapes.py` and `regen_sesv2_shapes.py` each name a botocore model and an output
+file and hand the rest to `main()`. The output keeps only what `RequestShapeModel` reads: the input
+shape of every operation, reduced to the members carried in the JSON body, and for every shape
+reachable from one, its type and the shapes of its members, list elements or map values.
+
+Members bound to the URI, the query string or a header are left out: they never reach the body.
+A model without such members, as DynamoDB's, comes out whole.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+from regen_partitions import load_model as load_json_model
+from regen_partitions import resolve_botocore_data, service_model, strip_source
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def load_model(data: Path, model: Path) -> dict:
+ """The `service-2.json` in the botocore version directory `model`, plain or gzipped."""
+ source = service_model(data / model)
+ if source is None:
+ raise SystemExit(f"error: no service model found in {data / model}")
+ return load_json_model(source)
+
+
+def build(model: dict, provenance: str, generator: str) -> dict:
+ shapes = model["shapes"]
+ kept: dict[str, dict] = {}
+
+ def keep(name: str, body_only: bool = False) -> None:
+ if name in kept:
+ return
+ shape = shapes[name]
+ kind = shape["type"]
+ entry: dict = {"type": kind}
+ kept[name] = entry
+ if kind == "structure":
+ members = {member: spec for member, spec in shape.get("members", {}).items()
+ if not (body_only and "location" in spec)}
+ entry["members"] = {member: spec["shape"] for member, spec in members.items()}
+ for spec in members.values():
+ keep(spec["shape"])
+ elif kind == "list":
+ entry["member"] = shape["member"]["shape"]
+ keep(shape["member"]["shape"])
+ elif kind == "map":
+ entry["value"] = shape["value"]["shape"]
+ keep(shape["value"]["shape"])
+
+ operations = {}
+ for name, operation in sorted(model["operations"].items()):
+ if "input" in operation:
+ operations[name] = operation["input"]["shape"]
+ keep(operation["input"]["shape"], body_only=True)
+
+ return {
+ "_source": {
+ "generator": generator,
+ "botocore": provenance,
+ },
+ "operations": operations,
+ "shapes": dict(sorted(kept.items())),
+ }
+
+
+def render(doc: dict) -> str:
+ return json.dumps(doc, indent=2, sort_keys=False) + "\n"
+
+
+def generator_name(script: str) -> str:
+ """The script's path from the repository root, as the vendored file's `_source` records it, or
+ its file name when it runs from outside the repository."""
+ path = Path(script).resolve()
+ return path.relative_to(REPO_ROOT).as_posix() if path.is_relative_to(REPO_ROOT) else path.name
+
+
+def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str) -> int:
+ parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
+ parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
+ parser.add_argument("--output", type=Path, default=output, help=argparse.SUPPRESS)
+ args = parser.parse_args(argv)
+
+ data, provenance = resolve_botocore_data(args.botocore_data)
+ fresh = render(build(load_model(data, model), provenance, generator_name(script)))
+
+ if args.check:
+ current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
+ if strip_source(current) != strip_source(fresh):
+ print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
+ return 1
+ return 0
+
+ args.output.write_text(fresh, encoding="utf-8")
+ shown = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output
+ print(f"wrote {shown} from {provenance}")
+ return 0
diff --git a/tools/aws/test_regen_dynamodb_shapes.py b/tools/aws/test_regen_dynamodb_shapes.py
deleted file mode 100644
index a5dfc584ef..0000000000
--- a/tools/aws/test_regen_dynamodb_shapes.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""Tests for regen_dynamodb_shapes.
-
-Run with: pytest tools/aws -q (or: make aws-data-test)
-"""
-from __future__ import annotations
-
-import regen_dynamodb_shapes as r
-
-
-MODEL = {
- "operations": {
- "Scan": {"input": {"shape": "ScanInput"}, "output": {"shape": "ScanOutput"}},
- "DescribeLimits": {"input": {"shape": "DescribeLimitsInput"}},
- "NoInput": {},
- },
- "shapes": {
- "ScanInput": {"type": "structure", "members": {
- "TableName": {"shape": "TableName"},
- "AttributesToGet": {"shape": "AttributeNameList"},
- "ExclusiveStartKey": {"shape": "Key"},
- }},
- "ScanOutput": {"type": "structure", "members": {"Count": {"shape": "Integer"}}},
- "DescribeLimitsInput": {"type": "structure", "members": {}},
- "TableName": {"type": "string", "min": 3},
- "AttributeNameList": {"type": "list", "member": {"shape": "AttributeName"}},
- "AttributeName": {"type": "string"},
- "Key": {"type": "map", "key": {"shape": "AttributeName"}, "value": {"shape": "AttributeValue"}},
- "AttributeValue": {"type": "structure", "members": {"S": {"shape": "AttributeName"}}},
- "Integer": {"type": "integer"},
- },
-}
-
-
-def test_keeps_only_input_shapes_and_their_types():
- doc = r.build(MODEL, "botocore test")
-
- assert doc["_source"] == {"generator": "tools/aws/regen_dynamodb_shapes.py", "botocore": "botocore test"}
- assert doc["operations"] == {"DescribeLimits": "DescribeLimitsInput", "Scan": "ScanInput"}
- assert "ScanOutput" not in doc["shapes"]
- assert "Integer" not in doc["shapes"]
- assert doc["shapes"]["ScanInput"] == {"type": "structure", "members": {
- "TableName": "TableName", "AttributesToGet": "AttributeNameList", "ExclusiveStartKey": "Key"}}
- assert doc["shapes"]["TableName"] == {"type": "string"}
- assert doc["shapes"]["AttributeNameList"] == {"type": "list", "member": "AttributeName"}
- assert doc["shapes"]["Key"] == {"type": "map", "value": "AttributeValue"}
-
-
-def test_check_ignores_provenance(tmp_path, monkeypatch):
- output = tmp_path / "shapes.json"
- output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
- monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
- monkeypatch.setattr(r, "load_model", lambda data: MODEL)
-
- assert r.main(["--check", "--output", str(output)]) == 0
-
-
-def test_check_reports_changed_shapes(tmp_path, monkeypatch):
- output = tmp_path / "shapes.json"
- changed = {**MODEL, "shapes": {**MODEL["shapes"], "TableName": {"type": "integer"}}}
- output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
- monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
- monkeypatch.setattr(r, "load_model", lambda data: MODEL)
-
- assert r.main(["--check", "--output", str(output)]) == 1
-
-
-def test_output_is_stable():
- first = r.render(r.build(MODEL, "botocore test"))
- second = r.render(r.build(MODEL, "botocore test"))
-
- assert first == second
- assert first.endswith("\n")
diff --git a/tools/aws/test_regen_sesv2_shapes.py b/tools/aws/test_regen_sesv2_shapes.py
deleted file mode 100644
index de7cd9174b..0000000000
--- a/tools/aws/test_regen_sesv2_shapes.py
+++ /dev/null
@@ -1,76 +0,0 @@
-"""Tests for regen_sesv2_shapes.
-
-Run with: pytest tools/aws -q (or: make aws-data-test)
-"""
-from __future__ import annotations
-
-import regen_sesv2_shapes as r
-
-
-MODEL = {
- "operations": {
- "SendEmail": {"input": {"shape": "SendEmailRequest"}, "output": {"shape": "SendEmailResponse"}},
- "GetEmailIdentity": {"input": {"shape": "GetEmailIdentityRequest"}},
- "NoInput": {},
- },
- "shapes": {
- "SendEmailRequest": {"type": "structure", "members": {
- "FromEmailAddress": {"shape": "EmailAddress"},
- "ReplyToAddresses": {"shape": "EmailAddressList"},
- "Content": {"shape": "EmailContent"},
- }},
- "SendEmailResponse": {"type": "structure", "members": {"MessageId": {"shape": "OutboundMessageId"}}},
- "GetEmailIdentityRequest": {"type": "structure", "members": {
- "EmailIdentity": {"shape": "Identity", "location": "uri", "locationName": "EmailIdentity"},
- "NextToken": {"shape": "NextToken", "location": "querystring", "locationName": "NextToken"},
- }},
- "EmailAddress": {"type": "string"},
- "EmailAddressList": {"type": "list", "member": {"shape": "EmailAddress"}},
- "EmailContent": {"type": "structure", "members": {"Raw": {"shape": "RawMessage"}}},
- "RawMessage": {"type": "structure", "members": {"Data": {"shape": "RawMessageData"}}},
- "RawMessageData": {"type": "blob"},
- "OutboundMessageId": {"type": "string"},
- "Identity": {"type": "string", "min": 1},
- "NextToken": {"type": "string"},
- },
-}
-
-
-def test_keeps_only_body_members_of_input_shapes():
- doc = r.build(MODEL, "botocore test")
-
- assert doc["_source"] == {"generator": "tools/aws/regen_sesv2_shapes.py", "botocore": "botocore test"}
- assert doc["operations"] == {"GetEmailIdentity": "GetEmailIdentityRequest", "SendEmail": "SendEmailRequest"}
- assert "SendEmailResponse" not in doc["shapes"]
- assert "OutboundMessageId" not in doc["shapes"]
- assert doc["shapes"]["SendEmailRequest"] == {"type": "structure", "members": {
- "FromEmailAddress": "EmailAddress", "ReplyToAddresses": "EmailAddressList", "Content": "EmailContent"}}
- assert doc["shapes"]["EmailAddressList"] == {"type": "list", "member": "EmailAddress"}
- assert doc["shapes"]["RawMessageData"] == {"type": "blob"}
-
-
-def test_drops_uri_and_query_members():
- doc = r.build(MODEL, "botocore test")
-
- assert doc["shapes"]["GetEmailIdentityRequest"] == {"type": "structure", "members": {}}
- assert "Identity" not in doc["shapes"]
- assert "NextToken" not in doc["shapes"]
-
-
-def test_check_ignores_provenance(tmp_path, monkeypatch):
- output = tmp_path / "shapes.json"
- output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
- monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
- monkeypatch.setattr(r, "load_model", lambda data, model: MODEL)
-
- assert r.main(["--check", "--output", str(output)]) == 0
-
-
-def test_check_reports_changed_shapes(tmp_path, monkeypatch):
- output = tmp_path / "shapes.json"
- changed = {**MODEL, "shapes": {**MODEL["shapes"], "EmailAddress": {"type": "integer"}}}
- output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
- monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
- monkeypatch.setattr(r, "load_model", lambda data, model: MODEL)
-
- assert r.main(["--check", "--output", str(output)]) == 1
diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py
new file mode 100644
index 0000000000..ce8a49ea5b
--- /dev/null
+++ b/tools/aws/test_request_shapes.py
@@ -0,0 +1,177 @@
+"""Tests for request_shapes, the generator behind regen_dynamodb_shapes and regen_sesv2_shapes.
+
+Run with: pytest tools/aws -q (or: make aws-data-test)
+"""
+from __future__ import annotations
+
+import gzip
+import json
+from pathlib import Path
+
+import pytest
+
+import regen_dynamodb_shapes
+import regen_sesv2_shapes
+import request_shapes as r
+
+
+DYNAMODB_MODEL = {
+ "operations": {
+ "Scan": {"input": {"shape": "ScanInput"}, "output": {"shape": "ScanOutput"}},
+ "DescribeLimits": {"input": {"shape": "DescribeLimitsInput"}},
+ "NoInput": {},
+ },
+ "shapes": {
+ "ScanInput": {"type": "structure", "members": {
+ "TableName": {"shape": "TableName"},
+ "AttributesToGet": {"shape": "AttributeNameList"},
+ "ExclusiveStartKey": {"shape": "Key"},
+ }},
+ "ScanOutput": {"type": "structure", "members": {"Count": {"shape": "Integer"}}},
+ "DescribeLimitsInput": {"type": "structure", "members": {}},
+ "TableName": {"type": "string", "min": 3},
+ "AttributeNameList": {"type": "list", "member": {"shape": "AttributeName"}},
+ "AttributeName": {"type": "string"},
+ "Key": {"type": "map", "key": {"shape": "AttributeName"}, "value": {"shape": "AttributeValue"}},
+ "AttributeValue": {"type": "structure", "members": {"S": {"shape": "AttributeName"}}},
+ "Integer": {"type": "integer"},
+ },
+}
+
+
+SESV2_MODEL = {
+ "operations": {
+ "SendEmail": {"input": {"shape": "SendEmailRequest"}, "output": {"shape": "SendEmailResponse"}},
+ "GetEmailIdentity": {"input": {"shape": "GetEmailIdentityRequest"}},
+ "NoInput": {},
+ },
+ "shapes": {
+ "SendEmailRequest": {"type": "structure", "members": {
+ "FromEmailAddress": {"shape": "EmailAddress"},
+ "ReplyToAddresses": {"shape": "EmailAddressList"},
+ "Content": {"shape": "EmailContent"},
+ }},
+ "SendEmailResponse": {"type": "structure", "members": {"MessageId": {"shape": "OutboundMessageId"}}},
+ "GetEmailIdentityRequest": {"type": "structure", "members": {
+ "EmailIdentity": {"shape": "Identity", "location": "uri", "locationName": "EmailIdentity"},
+ "NextToken": {"shape": "NextToken", "location": "querystring", "locationName": "NextToken"},
+ }},
+ "EmailAddress": {"type": "string"},
+ "EmailAddressList": {"type": "list", "member": {"shape": "EmailAddress"}},
+ "EmailContent": {"type": "structure", "members": {"Raw": {"shape": "RawMessage"}}},
+ "RawMessage": {"type": "structure", "members": {"Data": {"shape": "RawMessageData"}}},
+ "RawMessageData": {"type": "blob"},
+ "OutboundMessageId": {"type": "string"},
+ "Identity": {"type": "string", "min": 1},
+ "NextToken": {"type": "string"},
+ },
+}
+
+
+def test_keeps_only_input_shapes_and_their_types():
+ doc = r.build(DYNAMODB_MODEL, "botocore test", "tools/aws/regen_dynamodb_shapes.py")
+
+ assert doc["_source"] == {"generator": "tools/aws/regen_dynamodb_shapes.py", "botocore": "botocore test"}
+ assert doc["operations"] == {"DescribeLimits": "DescribeLimitsInput", "Scan": "ScanInput"}
+ assert "ScanOutput" not in doc["shapes"]
+ assert "Integer" not in doc["shapes"]
+ assert doc["shapes"]["ScanInput"] == {"type": "structure", "members": {
+ "TableName": "TableName", "AttributesToGet": "AttributeNameList", "ExclusiveStartKey": "Key"}}
+ assert doc["shapes"]["TableName"] == {"type": "string"}
+ assert doc["shapes"]["AttributeNameList"] == {"type": "list", "member": "AttributeName"}
+ assert doc["shapes"]["Key"] == {"type": "map", "value": "AttributeValue"}
+
+
+def test_keeps_only_body_members_of_input_shapes():
+ doc = r.build(SESV2_MODEL, "botocore test", "tools/aws/regen_sesv2_shapes.py")
+
+ assert doc["_source"] == {"generator": "tools/aws/regen_sesv2_shapes.py", "botocore": "botocore test"}
+ assert doc["operations"] == {"GetEmailIdentity": "GetEmailIdentityRequest", "SendEmail": "SendEmailRequest"}
+ assert "SendEmailResponse" not in doc["shapes"]
+ assert "OutboundMessageId" not in doc["shapes"]
+ assert doc["shapes"]["SendEmailRequest"] == {"type": "structure", "members": {
+ "FromEmailAddress": "EmailAddress", "ReplyToAddresses": "EmailAddressList", "Content": "EmailContent"}}
+ assert doc["shapes"]["EmailAddressList"] == {"type": "list", "member": "EmailAddress"}
+ assert doc["shapes"]["RawMessageData"] == {"type": "blob"}
+
+
+def test_drops_uri_and_query_members():
+ doc = r.build(SESV2_MODEL, "botocore test", "tools/aws/regen_sesv2_shapes.py")
+
+ assert doc["shapes"]["GetEmailIdentityRequest"] == {"type": "structure", "members": {}}
+ assert "Identity" not in doc["shapes"]
+ assert "NextToken" not in doc["shapes"]
+
+
+def _main(output: Path) -> int:
+ return r.main(["--check", "--output", str(output)], script=r.__file__, model=Path("svc/service-2.json"),
+ output=output, description="test")
+
+
+def test_check_ignores_provenance(tmp_path, monkeypatch):
+ output = tmp_path / "shapes.json"
+ output.write_text(r.render(r.build(DYNAMODB_MODEL, "botocore 0.0.1 (local/aws/botocore)",
+ "tools/aws/regen_test_shapes.py")), encoding="utf-8")
+ monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
+ monkeypatch.setattr(r, "load_model", lambda data, model: DYNAMODB_MODEL)
+
+ assert _main(output) == 0
+
+
+def test_check_reports_changed_shapes(tmp_path, monkeypatch):
+ output = tmp_path / "shapes.json"
+ changed = {**DYNAMODB_MODEL, "shapes": {**DYNAMODB_MODEL["shapes"], "TableName": {"type": "integer"}}}
+ output.write_text(r.render(r.build(changed, "botocore test", "tools/aws/regen_test_shapes.py")),
+ encoding="utf-8")
+ monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
+ monkeypatch.setattr(r, "load_model", lambda data, model: DYNAMODB_MODEL)
+
+ assert _main(output) == 1
+
+
+def test_output_is_stable():
+ first = r.render(r.build(DYNAMODB_MODEL, "botocore test", "tools/aws/regen_dynamodb_shapes.py"))
+ second = r.render(r.build(DYNAMODB_MODEL, "botocore test", "tools/aws/regen_dynamodb_shapes.py"))
+
+ assert first == second
+ assert first.endswith("\n")
+
+
+def test_generator_name_is_the_scripts_path_from_the_repository_root():
+ assert r.generator_name(regen_dynamodb_shapes.__file__) == "tools/aws/regen_dynamodb_shapes.py"
+ assert r.generator_name(regen_sesv2_shapes.__file__) == "tools/aws/regen_sesv2_shapes.py"
+
+
+def test_generator_name_outside_the_repository_is_the_file_name(tmp_path):
+ assert r.generator_name(str(tmp_path / "regen_copy_shapes.py")) == "regen_copy_shapes.py"
+
+
+def test_load_model_reads_a_gzipped_service_model(tmp_path):
+ version = tmp_path / "svc" / "2020-01-01"
+ version.mkdir(parents=True)
+ with gzip.open(version / "service-2.json.gz", "wt", encoding="utf-8") as f:
+ json.dump(SESV2_MODEL, f)
+
+ assert r.load_model(tmp_path, Path("svc/2020-01-01")) == SESV2_MODEL
+
+
+def test_load_model_without_a_service_model_exits(tmp_path):
+ with pytest.raises(SystemExit):
+ r.load_model(tmp_path, Path("svc/2020-01-01"))
+
+
[email protected]("script, model, output", [
+ (regen_dynamodb_shapes, "dynamodb/2012-08-10", "dynamodb-request-shapes.json"),
+ (regen_sesv2_shapes, "sesv2/2019-09-27", "sesv2-request-shapes.json"),
+])
+def test_each_script_runs_the_shared_main_with_its_model_and_output(script, model, output, monkeypatch):
+ calls = []
+ monkeypatch.setattr(r, "main", lambda argv, **kwargs: calls.append((argv, kwargs)) or 0)
+
+ assert script.main(["--check"]) == 0
+ assert calls == [(["--check"], {
+ "script": script.__file__,
+ "model": Path(model),
+ "output": r.REPO_ROOT / "src/main/resources/aws" / output,
+ "description": script.__doc__,
+ })]