Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Add Cost Usage Reports Service (#615)

staranto904f0f7a21cb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 880c4d80..ef25e4f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [Unreleased]
+
+### Added
+- **Cost & Usage Reports** — 7 of 7 CUR API actions supported.
## [1.3.35] — 2026-05-11
### Fixed
@@ -422,7 +426,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [1.3.6] — 2026-04-20
### Added
-- **API Gateway path-based data plane** — REST + HTTP + WebSocket APIs are now reachable without `*.execute-api.localhost` Host overrides: `http(s)://localhost:4566/_aws/execute-api/{apiId}/{stage}/{path}` (v1 + v2 HTTP + v2 WS) and the LocalStack-legacy `http://localhost:4566/restapis/{apiId}/{stage}/_user_request_/{path}` (v1). Unblocks macOS browsers (no `*.localhost` DNS resolution) and strict HTTP clients with no Host override.
+- **API Gateway path-based data plane** — REST + HTTP + WebSocket APIs are now reachable without `*.execute-api.localhost` Host overrides: `http(s)://localhost:4566/_aws/execute-api/{apiId}/{stage}/{path}` (v1 + v2 HTTP + v2 WS) and the LocalStack-legacy `http://localhost:4566/restapis/{apiId}/{stage}/_user_request_/{path}` (v1). Unblocks macOS browsers (no `*.localhost` DNS resolution) and strict HTTP clients with no Host override.
- **Custom/predictable API Gateway IDs** — `aws_apigatewayv2_api` and `aws_apigateway_rest_api` honour an `ms-custom-id` tag on `CreateApi` / `CreateRestApi` and pin the generated `apiId` / REST API id to the tag value. Duplicates in the same account return `ConflictException` (409). The LocalStack `ls-custom-id` tag is intentionally rejected with a clear `BadRequestException` (400) pointing callers at the ministack-native key. Reported by @whittin3. Fixes #400
- **Cognito `AWS::Cognito::UserPoolClient` CFN `GenerateSecret`** — CloudFormation-provisioned user pool clients now generate a client secret when `GenerateSecret: true`, matching the native Cognito API path. Contributed by @mgius-ae (#403)
@@ -663,7 +667,7 @@ These services stored per-tenant data in plain `dict` / `list`, so `List*` / `De
## [1.2.18] — 2026-04-15
### Fixed
-- **ECS services/tasks invisible when created via CloudFormation** — CF provisioner stored services with ARN keys instead of `cluster/name`, causing `list-services` and `list-tasks` to return empty. Fixed key format, added task spawning on service create/update/delete, and replaced stale tasks on task definition updates. CF provisioner now delegates to the ECS module for a single code path. Reported by @Vagator-Prostovich
+- **ECS services/tasks invisible when created via CloudFormation** — CF provisioner stored services with ARN keys instead of `cluster/name`, causing `list-services` and `list-tasks` to return empty. Fixed key format, added task spawning on service create/update/delete, and replaced stale tasks on task definition updates. CF provisioner now delegates to the ECS module for a single code path. Reported by @Vagator-Prostovich
- **ECS CF container definitions PascalCase mismatch** — CloudFormation container definitions used PascalCase keys (`Name`, `Image`, `PortMappings`) but the ECS runtime expected camelCase, causing `KeyError` when spawning tasks. Added `_normalize_container_defs` to convert keys.
- **ECS `_task_def_latest` stored string instead of integer** — CF provisioner stored `"family:1"` instead of `1`, producing malformed keys like `"family:family:1"` on subsequent registrations.
- **ECS CF task definition and service delete used wrong keys** — delete handlers used ARN but dicts were keyed by `family:revision` and `cluster/name` respectively.
@@ -711,7 +715,7 @@ These services stored per-tenant data in plain `dict` / `list`, so `List*` / `De
- **EC2 AuthorizeSecurityGroup returns rules** — `AuthorizeSecurityGroupIngress` and `AuthorizeSecurityGroupEgress` now return `SecurityGroupRules` in the response with rule IDs, group ownership, protocol, port range, and CIDR details. Required by Terraform AWS provider v6. Reported by @mspiller (#325)
### Fixed
-- **Cognito token claims correctness** — `origin_jti` and `auth_time` claims are now only included in `IdToken` and `AccessToken` (not `RefreshToken`), matching real AWS Cognito behavior. Refresh tokens use minimal claims with only `client_id`.
+- **Cognito token claims correctness** — `origin_jti` and `auth_time` claims are now only included in `IdToken` and `AccessToken` (not `RefreshToken`), matching real AWS Cognito behavior. Refresh tokens use minimal claims with only `client_id`.
---
@@ -795,7 +799,7 @@ These services stored per-tenant data in plain `dict` / `list`, so `List*` / `De
## [1.2.7] — 2026-04-12
### Added
-- **EC2 CreateDefaultVpc** — new action creates a default VPC with all associated resources (3 default subnets, internet gateway, route table, network ACL, security group), matching real AWS behavior. Returns `DefaultVpcAlreadyExists` if one already exists. Reported by @staranto
+- **EC2 CreateDefaultVpc** — new action creates a default VPC with all associated resources (3 default subnets, internet gateway, route table, network ACL, security group), matching real AWS behavior. Returns `DefaultVpcAlreadyExists` if one already exists. Reported by @staranto
- **DynamoDB ExecuteStatement (PartiQL)** — supports `SELECT`, `INSERT`, `UPDATE`, `DELETE` PartiQL statements with `?` parameter binding. Enables IntelliJ database integration and other PartiQL-based tooling. Reported by @mspiller
- **SNS FIFO topic support** — `.fifo` naming validation, `MessageGroupId`/`MessageDeduplicationId` enforcement, 5-minute deduplication window, sequence numbers, content-based deduplication, FIFO SQS subscription validation, `PublishBatch` FIFO support, thread-safe dedup cache. Contributed by @yskarparis (#279)
@@ -1061,7 +1065,7 @@ and reference by the sha256 over the code image. In the future this should be a
- **RDS Data API service** — `ExecuteStatement`, `BatchExecuteStatement`, `BeginTransaction`, `CommitTransaction`, `RollbackTransaction`. Routes SQL to the real database containers MiniStack spins up for RDS instances. Supports both MySQL and PostgreSQL engines. Contributed by @jayjanssen (#193)
### Fixed
-- **CDK deploy "implicit NaN" deserialization error** — the CloudFormation SSM provisioner stored `LastModifiedDate` as an ISO 8601 string instead of a Unix epoch float. The JS SDK v3 (bundled in CDK CLI) uses `AwsJson1_1Protocol` for SSM and calls `parseEpochTimestamp()` on the value, which expects a number. `cdk deploy` would fail immediately after bootstrap when checking the SSM bootstrap version parameter. Reported by @youngkwangk @jolo-dev and @ben-shearlaw
+- **CDK deploy "implicit NaN" deserialization error** — the CloudFormation SSM provisioner stored `LastModifiedDate` as an ISO 8601 string instead of a Unix epoch float. The JS SDK v3 (bundled in CDK CLI) uses `AwsJson1_1Protocol` for SSM and calls `parseEpochTimestamp()` on the value, which expects a number. `cdk deploy` would fail immediately after bootstrap when checking the SSM bootstrap version parameter. Reported by @youngkwangk @jolo-dev and @ben-shearlaw
- **RDS Data API thread safety** — added `threading.Lock` to protect transaction state against concurrent access
- **RDS Data API parameter binding** — `ExecuteStatement` and `BatchExecuteStatement` now convert RDS Data API `:name` parameters to DB-API parameterized queries instead of ignoring them
- **RDS Data API connection leak** — connections are now properly closed on exceptions in non-transaction execute paths
@@ -1541,7 +1545,7 @@ Thanks to @moabukar for #104 (error handling, routing conflicts, persistence har
- **Lambda handler validation** — returns proper `Runtime.InvalidEntrypoint` error if handler name has no `.` separator instead of crashing
- **RDS error code** — `DBInstanceAlreadyExists` corrected to `DBInstanceAlreadyExistsFault` matching AWS error codes
-- Thanks to @lubond @jimmyd-be @abedurftig @mig_mit for reporting issues and testing
+- Thanks to @lubond @jimmyd-be @abedurftig @mig_mit for reporting issues and testing
- Thanks to @jv2222 and @santiagodoldan for their massive contributions
### Tests
@@ -1705,7 +1709,7 @@ Thanks to @moabukar for #104 (error handling, routing conflicts, persistence har
## [1.1.7] — 2026-03-30
### Added
-- **Athena engine control** — new `ATHENA_ENGINE` env var (`auto` | `duckdb` | `mock`) to select the SQL backend at startup; `auto` keeps existing behaviour (DuckDB if installed, mock otherwise). New `/_ministack/config` endpoint accepts `POST {"athena.ATHENA_ENGINE": "mock"}` to switch engines at runtime without restart — useful in CI to force mock mode without DuckDB installed.
+- **Athena engine control** — new `ATHENA_ENGINE` env var (`auto` | `duckdb` | `mock`) to select the SQL backend at startup; `auto` keeps existing behaviour (DuckDB if installed, mock otherwise). New `/_ministack/config` endpoint accepts `POST {"athena.ATHENA_ENGINE": "mock"}` to switch engines at runtime without restart — useful in CI to force mock mode without DuckDB installed.
- **VPC gap coverage** — 6 new EC2 resource types, 22 new actions, 11 new tests
- **NAT Gateways**: `CreateNatGateway`, `DescribeNatGateways`, `DeleteNatGateway` — supports `SubnetId`, `ConnectivityType` (public/private), state transitions, `vpc-id`/`subnet-id`/`state` filters
- **Network ACLs**: `CreateNetworkAcl`, `DescribeNetworkAcls`, `DeleteNetworkAcl`, `CreateNetworkAclEntry`, `DeleteNetworkAclEntry`, `ReplaceNetworkAclEntry`, `ReplaceNetworkAclAssociation` — full CRUD with rule entries and subnet associations
diff --git a/README.md b/README.md
index 341a6535..a13c1c8a 100644
--- a/README.md
+++ b/README.md
@@ -379,6 +379,8 @@ subnet = ec2.create_subnet(
| **CloudFront KeyValueStore (data plane)** | DescribeKeyValueStore, ListKeys, GetKey, PutKey, DeleteKey, UpdateKeys | Separate `cloudfront-keyvaluestore` SDK service (REST/JSON, signing name `cloudfront-keyvaluestore`); ETag-based optimistic concurrency on every mutating op; `UpdateKeys` is atomic (validates whole batch, rejects on first invalid entry); `ListKeys` paginates with opaque `NextToken` capped at 50 results per AWS spec; bridges to the management plane via the shared KVS ARN |
| **CloudTrail** | LookupEvents, CreateTrail, DeleteTrail, GetTrail, DescribeTrails, ListTrails, UpdateTrail, GetTrailStatus, StartLogging, StopLogging, PutEventSelectors, GetEventSelectors, AddTags, ListTags, RemoveTags | In-memory audit log; recording opt-in via `CLOUDTRAIL_RECORDING=1` (or runtime config endpoint); per-account ring buffer (`CLOUDTRAIL_MAX_EVENTS=10000`); `LookupEvents` supports all 8 AWS `LookupAttributes`; `IsLogging` flips on Start/StopLogging |
| **Resource Groups** | CreateGroup, GetGroup, DeleteGroup, UpdateGroup, ListGroups, GetGroupQuery, UpdateGroupQuery, GetGroupConfiguration, PutGroupConfiguration, GroupResources, UngroupResources, ListGroupResources, ListGroupingStatuses, SearchResources, Tag, Untag, GetTags, GetAccountSettings, UpdateAccountSettings | 19 of 23 spec ops; tag-sync ops omitted (not exposed by AWS CLI / Terraform); `Group` accepts bare name or full ARN |
+| **Cost & Usage Reports** | DeleteReportDefinition, DescribeReportDefinitions, ListTagsForResource, ModifyReportDefinition, PutReportDefinition, TagResource, UntagResource | 7 of 7 spec ops |
+
### CloudFormation
@@ -760,7 +762,7 @@ Install DuckDB for full Athena SQL compatibility: `pip install ministack[full]`.
When `PERSIST_STATE=1`, MiniStack saves service state to `STATE_DIR` on shutdown and reloads it on startup. Writes are atomic (write-to-tmp then rename) to prevent corruption on crash.
-Services currently supporting persistence: **All services** — API Gateway v1/v2, ALB, ACM, AppConfig, AppSync, Athena, Cloud Map, CloudFront, CloudWatch, CloudWatch Logs, CodeBuild, Cognito, DynamoDB, EC2, ECR, ECS, EFS, EKS, ElastiCache, EMR, EventBridge, EventBridge Scheduler, Firehose, Glue, IAM/STS, Kinesis, KMS, Lambda, RDS, Route 53, S3, Secrets Manager, SES, SES v2, SNS, SQS, SSM, Step Functions, Transfer Family, WAF v2
+Services currently supporting persistence: **All services** — API Gateway v1/v2, ALB, ACM, AppConfig, AppSync, Athena, Cloud Map, CloudFront, CloudWatch, CloudWatch Logs, CodeBuild, Cognito, DynamoDB, EC2, ECR, ECS, EFS, EKS, ElastiCache, EMR, EventBridge, EventBridge Scheduler, Firehose, Glue, IAM/STS, Kinesis, KMS, Lambda, RDS, Route 53, S3, Secrets Manager, SES, SES v2, SNS, SQS, SSM, Step Functions, Transfer Family, WAF v2
```bash
docker run -p 4566:4566 \
diff --git a/ministack/app.py b/ministack/app.py
index d36a6018..3c52320b 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -96,7 +96,7 @@ _NON_S3_VHOST_NAMES = frozenset({
"s3", "s3-control", "sqs", "sns", "dynamodb", "lambda", "iam", "sts",
"secretsmanager", "logs", "ssm", "events", "kinesis", "monitoring", "ses",
"states", "ecs", "rds", "rds-data", "elasticache", "glue", "athena",
- "apigateway", "cloudformation", "autoscaling", "codebuild", "transfer",
+ "apigateway", "cloudformation", "autoscaling", "codebuild", "transfer", "cur",
"cloudfront-kvs",
"appsync-api", "appsync-realtime-api",
})
@@ -252,6 +252,7 @@ SERVICE_REGISTRY = {
"waf-regional": {"module": "waf_v1"},
"wafv2": {"module": "waf"},
"cloudtrail": {"module": "cloudtrail"},
+ "cur": {"module": "cur"},
}
SERVICE_HANDLERS = {
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 26413e46..42a4ebc9 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -330,6 +330,11 @@ SERVICE_PATTERNS = {
"host_patterns": [r"cloudtrail\."],
"credential_scope": "cloudtrail",
},
+ "cur": {
+ "target_prefixes": ["AWSOrigamiServiceGateway"],
+ "host_patterns": [r"cur\."],
+ "credential_scope": "cur",
+ },
}
@@ -409,6 +414,7 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"tagging": "tagging",
"resource-groups": "resource-groups",
"cloudtrail": "cloudtrail",
+ "cur": "cur",
}
if svc_name in scope_map:
return scope_map[svc_name]
diff --git a/ministack/services/cur.py b/ministack/services/cur.py
new file mode 100644
index 00000000..252e7053
--- /dev/null
+++ b/ministack/services/cur.py
@@ -0,0 +1,248 @@
+"""
+AWS Cost and Usage Report (CUR) service emulator.
+
+JSON 1.1 protocol with X-Amz-Target prefix ``AWSOrigamiServiceGateway``.
+
+Implemented:
+ DeleteReportDefinition, DescribeReportDefinitions, ListTagsForResource,
+ ModifyReportDefinition, PutReportDefinition, TagResource, UntagResource.
+
+Deferred:
+ None.
+"""
+
+import copy
+import json
+import logging
+
+from ministack.core.responses import (
+ AccountScopedDict,
+ error_response_json,
+)
+
+logger = logging.getLogger("cur")
+
+_report_definitions = AccountScopedDict() # report_name -> report_definition
+_report_tags = AccountScopedDict() # report_name -> {tag_key: tag_value}
+
+
+def reset():
+ _report_definitions.clear()
+ _report_tags.clear()
+
+
+def get_state():
+ return {
+ "report_definitions": copy.deepcopy(_report_definitions),
+ "report_tags": copy.deepcopy(_report_tags),
+ }
+
+
+def restore_state(data):
+ if not data:
+ return
+ _report_definitions.clear()
+ _report_definitions.update(data.get("report_definitions") or {})
+ _report_tags.clear()
+ _report_tags.update(data.get("report_tags") or {})
+
+
+def load_persisted_state(data):
+ restore_state(data)
+
+
+def _json(status: int, body: dict):
+ return status, {"Content-Type": "application/x-amz-json-1.1"}, json.dumps(body).encode()
+
+
+def _delete_report_definition(payload: dict):
+ report_name = payload.get("ReportName")
+
+ if not isinstance(report_name, str) or not report_name.strip():
+ return error_response_json("ValidationException", "ReportName is required", 400)
+
+ if report_name not in _report_definitions:
+ return error_response_json(
+ "ValidationException",
+ f"Report definition not found: {report_name}",
+ 400,
+ )
+
+ _report_tags.pop(report_name, None)
+ del _report_definitions[report_name]
+ return _json(200, {})
+
+
+def _describe_report_definitions(_payload: dict):
+ return _json(
+ 200,
+ {
+ "ReportDefinitions": list(_report_definitions.values()),
+ },
+ )
+
+
+def _list_tags_for_resource(payload: dict):
+ report_name = payload.get("ReportName")
+ if not isinstance(report_name, str) or not report_name.strip():
+ return error_response_json("ValidationException", "ReportName is required", 400)
+
+ if report_name not in _report_definitions:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Report definition not found: {report_name}",
+ 400,
+ )
+
+ tag_dict = _report_tags.get(report_name, {})
+ tags = [{"Key": k, "Value": v} for k, v in tag_dict.items()]
+ return _json(200, {"Tags": tags})
+
+
+def _modify_report_definition(payload: dict):
+ report_name = payload.get("ReportName")
+ report = payload.get("ReportDefinition")
+
+ if not isinstance(report_name, str) or not report_name.strip():
+ return error_response_json("ValidationException", "ReportName is required", 400)
+
+ if not isinstance(report, dict):
+ return error_response_json("ValidationException", "ReportDefinition is required", 400)
+
+ if report_name not in _report_definitions:
+ return error_response_json(
+ "ValidationException",
+ f"Report definition not found: {report_name}",
+ 400,
+ )
+
+ # AWS uses the request ReportName as the identity of the report to update.
+ # Keep that stable even when a skeleton payload omits or changes
+ # ReportDefinition.ReportName.
+ updated = copy.deepcopy(report)
+ updated["ReportName"] = report_name
+
+ _report_definitions[report_name] = updated
+ return _json(200, {})
+
+
+def _put_report_definition(payload: dict):
+ report = payload.get("ReportDefinition")
+ if not isinstance(report, dict):
+ return error_response_json(
+ "ValidationException",
+ "ReportDefinition is required",
+ 400,
+ )
+
+ report_name = report.get("ReportName")
+ if not isinstance(report_name, str) or not report_name.strip():
+ return error_response_json(
+ "ValidationException",
+ "ReportDefinition.ReportName is required",
+ 400,
+ )
+
+ if report_name in _report_definitions:
+ return error_response_json(
+ "DuplicateReportNameException",
+ f"Report definition already exists: {report_name}",
+ 400,
+ )
+
+ _report_definitions[report_name] = copy.deepcopy(report)
+ _report_tags.setdefault(report_name, {})
+ return _json(200, {})
+
+
+def _tag_resource(payload: dict):
+ report_name = payload.get("ReportName")
+ if not isinstance(report_name, str) or not report_name.strip():
+ return error_response_json("ValidationException", "ReportName is required", 400)
+
+ if report_name not in _report_definitions:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Report definition not found: {report_name}",
+ 400,
+ )
+
+ tags = payload.get("Tags")
+ if not isinstance(tags, list):
+ return error_response_json("ValidationException", "Tags is required", 400)
+
+ # Validate each tag has Key and Value.
+ for tag in tags:
+ if not isinstance(tag, dict):
+ return error_response_json("ValidationException", "Tag must be a dict", 400)
+ if "Key" not in tag or "Value" not in tag:
+ return error_response_json(
+ "ValidationException",
+ "Each tag must have Key and Value",
+ 400,
+ )
+
+ # Merge tags into the report's tag dict.
+ tag_dict = _report_tags.setdefault(report_name, {})
+ for tag in tags:
+ tag_dict[tag["Key"]] = tag["Value"]
+
+ return _json(200, {})
+
+
+def _untag_resource(payload: dict):
+ report_name = payload.get("ReportName")
+ if not isinstance(report_name, str) or not report_name.strip():
+ return error_response_json("ValidationException", "ReportName is required", 400)
+
+ if report_name not in _report_definitions:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"Report definition not found: {report_name}",
+ 400,
+ )
+
+ tag_keys = payload.get("TagKeys")
+ if not isinstance(tag_keys, list):
+ return error_response_json("ValidationException", "TagKeys is required", 400)
+
+ # Remove tags by key.
+ tag_dict = _report_tags.get(report_name, {})
+ for key in tag_keys:
+ tag_dict.pop(key, None)
+
+ return _json(200, {})
+
+
+_DISPATCH = {
+ "DeleteReportDefinition": _delete_report_definition,
+ "DescribeReportDefinitions": _describe_report_definitions,
+ "ListTagsForResource": _list_tags_for_resource,
+ "ModifyReportDefinition": _modify_report_definition,
+ "PutReportDefinition": _put_report_definition,
+ "TagResource": _tag_resource,
+ "UntagResource": _untag_resource,
+}
+
+
+async def handle_request(method, path, headers, body, query_params):
+ target = headers.get("X-Amz-Target") or headers.get("x-amz-target") or ""
+ action = target.split(".", 1)[1] if "." in target else target
+ if not action:
+ return error_response_json("InvalidAction", "missing X-Amz-Target", 400)
+
+ body_text = body.decode("utf-8") if isinstance(body, bytes) else (body or "")
+ try:
+ payload = json.loads(body_text) if body_text else {}
+ except json.JSONDecodeError:
+ return error_response_json("SerializationException", "invalid JSON body", 400)
+
+ fn = _DISPATCH.get(action)
+ if fn is None:
+ return error_response_json(
+ "InvalidAction",
+ f"Operation '{action}' not implemented",
+ 400,
+ )
+
+ return fn(payload)
diff --git a/tests/conftest.py b/tests/conftest.py
index 74bb98cf..8d9202d7 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -438,3 +438,7 @@ def scheduler():
@pytest.fixture(scope="session")
def tagging():
return make_client("resourcegroupstaggingapi")
+
[email protected](scope="session")
+def cur():
+ return make_client("cur")
diff --git a/tests/test_cur.py b/tests/test_cur.py
new file mode 100644
index 00000000..3daaa98e
--- /dev/null
+++ b/tests/test_cur.py
@@ -0,0 +1,301 @@
+import uuid
+
+import pytest
+from botocore.exceptions import ClientError, ParamValidationError
+
+name_prefix = "cur-test"
+test_tags = [
+ { "Key": "kids", "Value": "zalkpz" },
+ { "Key": "dates", "Value": "091203060606" },
+]
+
+def _report_definition(name: str) -> dict:
+ return {
+ "ReportName": name,
+ "TimeUnit": "DAILY",
+ "Format": "textORcsv",
+ "Compression": "GZIP",
+ "AdditionalSchemaElements": ["RESOURCES"],
+ "S3Bucket": "cur-test-bucket",
+ "S3Prefix": "reports",
+ "S3Region": "us-east-1",
+ "AdditionalArtifacts": [],
+ "RefreshClosedReports": True,
+ "ReportVersioning": "OVERWRITE_REPORT",
+ }
+
+
+def _uid() -> str:
+ return uuid.uuid4().hex[:8]
+
+
+# -- DeleteReportDefinition ----------------------------------------------------
+
+
+def test_cur_delete_report_definition(cur):
+ name = f"{name_prefix}-{_uid()}"
+
+ # First create one and then we'll immediately delete it.
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+
+ deleted = cur.delete_report_definition(ReportName=name)
+ assert deleted["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+ reports = cur.describe_report_definitions()["ReportDefinitions"]
+ assert all(r["ReportName"] != name for r in reports)
+
+
+def test_cur_delete_report_definition_not_found(cur):
+ name = f"not-found-{_uid()}"
+
+ with pytest.raises(ClientError) as e:
+ cur.delete_report_definition(ReportName=name)
+
+ assert e.value.response["Error"]["Code"] =="ValidationException"
+ assert e.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+# -- DescribeReportDefinitions -------------------------------------------------
+
+
+def test_cur_describe_report_definitions(cur):
+ max = 4
+ name = f"{name_prefix}-{_uid()}"
+
+ # Create {max} report definitions.
+ for i in range(0, max):
+ cur.put_report_definition(
+ ReportDefinition=_report_definition(f"{name}-{i:02d}")
+ )
+
+ # Retrieve all report definitions. This will include the {max} just created,
+ # plus, potentially, any leftovers in the MiniStack state.
+ resp = cur.describe_report_definitions()
+ list = resp["ReportDefinitions"]
+
+ # Verify that each of the test reports exists.
+ for i in range(0, max):
+ assert any(r["ReportName"] == f"{name}-{i:02d}" for r in list)
+
+
+def test_cur_describe_report_definitions_empty(cur):
+
+ # Get all the report definitions and delete them so we're empty.
+ resp = cur.describe_report_definitions()
+ list = resp["ReportDefinitions"]
+
+ for definition in list:
+ cur.delete_report_definition(ReportName=definition["ReportName"])
+
+
+ # Get all the definitins again, which should be empty.
+ resp = cur.describe_report_definitions()
+ list = resp["ReportDefinitions"]
+
+ assert list == []
+
+
+# -- ModifyReportDefinition ----------------------------------------------------
+
+ # base = _report_definition(f"{name_prefix}-{_uid()}")
+ # modified = {**base, "S3Prefix": "xxx"}
+
+ # assert modified["S3Prefix"] == "xxx"
+ # assert all(modified[k] == v for k, v in base.items() if k != "S3Prefix")
+
+def test_cur_modify_report_definition(cur):
+ original_name = f"{name_prefix}-{_uid()}"
+ original = _report_definition(original_name)
+
+ # The second definition will have these items changed.
+ modified_name = f"{original_name}-modified"
+ modified = {
+ **original,
+ "ReportName": modified_name,
+ "Compression": "ZIP",
+ "S3Prefix": "new-prefix",
+ }
+
+ # Put both the original and modified definitions.
+ for r in [original, modified]:
+ cur.put_report_definition(ReportDefinition=r)
+
+ # Retrieve all the definitions and make sure the two that we just put
+ # actually exist.
+ resp = cur.describe_report_definitions()
+ created = [
+ r for r in resp["ReportDefinitions"]
+ if r["ReportName"].startswith(original_name)
+ ]
+
+ assert len(created) == 2
+ assert {r["ReportName"] for r in created} == {original_name, modified_name}
+
+ # Make sure the only the three test attributes were changed. Retrieve the
+ # two definitions from the created list and then compare them attribute-by-
+ # attribute.
+ by_name = {r["ReportName"]: r for r in created}
+ created_original = by_name[original_name]
+ created_modified = by_name[modified_name]
+
+ changed_keys = {"ReportName", "Compression", "S3Prefix"}
+
+ # Confirm changed attributes match expected values.
+ assert created_modified["ReportName"] == modified_name
+ assert created_modified["Compression"] == "ZIP"
+ assert created_modified["S3Prefix"] == "new-prefix"
+
+ # Confirm every other attribute is unchanged.
+ for k, v in created_original.items():
+ if k in changed_keys:
+ continue
+
+ assert created_modified[k] == v
+
+
+# -- PutReportDefinition -------------------------------------------------------
+
+
+def test_cur_put_report_definition(cur):
+ name = f"{name_prefix}-{_uid()}"
+
+ resp = cur.put_report_definition(
+ ReportDefinition=_report_definition(name)
+ )
+
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+ list = cur.describe_report_definitions()["ReportDefinitions"]
+ assert any(r["ReportName"] == name for r in list)
+
+
+def test_cur_put_report_definition_duplicate_name(cur):
+ name = f"{name_prefix}-{_uid()}"
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+
+ with pytest.raises(ClientError) as e:
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+
+ assert e.value.response["Error"]["Code"] == "DuplicateReportNameException"
+
+
+def test_cur_put_report_definition_missing_report_name(cur):
+ bad = _report_definition(f"{name_prefix}-{_uid()}")
+
+ # This is an invalid report definition, but it is not caught by Boto3 like
+ # the missing test below
+ bad["ReportName"] = " "
+
+ with pytest.raises(ClientError) as e:
+ cur.put_report_definition(ReportDefinition=bad)
+
+ assert e.value.response["Error"]["Code"] == "ValidationException"
+
+
+def test_cur_put_report_definition_missing_definition_body(cur):
+ # Note that we're checking ParamValidationError as opposed to the more
+ # typical ClientError. Boto3 is throwing this before the MiniStack client is
+ # hit.
+ with pytest.raises(ParamValidationError) as e:
+ cur.put_report_definition(ReportDefinition={})
+
+ assert "Missing required parameter in ReportDefinition" in str(e.value)
+
+
+# -- TagResource ---------------------------------------------------------------
+
+
+def test_cur_tag_resource(cur):
+ name = f"{name_prefix}-{_uid()}"
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+
+ resp = cur.tag_resource(
+ ReportName=name,
+ Tags=test_tags,
+ )
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+ tags = cur.list_tags_for_resource(ReportName=name)["Tags"]
+ assert len(tags) == 2
+ assert all(tag in tags for tag in test_tags)
+
+
+def test_cur_tag_resource_not_found(cur):
+ name = f"not-found-{_uid()}"
+
+ with pytest.raises(ClientError) as e:
+ cur.tag_resource(
+ ReportName=name,
+ Tags=[{"Key": "not", "Value": "found"}],
+ )
+
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert e.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_cur_tag_resource_overwrites(cur):
+ name = f"{name_prefix}-{_uid()}"
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+
+ # Add initial tags.
+ cur.tag_resource(
+ ReportName=name,
+ Tags=test_tags,
+ )
+
+ # Overwrite one tag, add another.
+ cur.tag_resource(
+ ReportName=name,
+ Tags=[
+ {"Key": "kids", "Value": "kpzzal"},
+ {"Key": "size", "Value": "6"},
+ ],
+ )
+
+ tags = cur.list_tags_for_resource(ReportName=name)["Tags"]
+ assert {"Key": "kids", "Value": "kpzzal"} in tags
+ assert {"Key": "dates", "Value": "091203060606"} in tags
+ assert {"Key": "size", "Value": "6"} in tags
+ # The original key/value should not exist.
+ assert {"Key": "kids", "Value": "zalkpz"} not in tags
+
+
+# -- UntagResource -------------------------------------------------------------
+
+
+def test_cur_untag_resource(cur):
+ name = f"{name_prefix}-{_uid()}"
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+ cur.tag_resource(ReportName=name, Tags=test_tags)
+
+ resp = cur.untag_resource(ReportName=name, TagKeys=["kids"])
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+ tags = cur.list_tags_for_resource(ReportName=name)["Tags"]
+ assert {"Key": "kids", "Value": "zalkpz"} not in tags
+ assert {"Key": "dates", "Value": "091203060606"} in tags
+
+
+def test_cur_untag_resource_not_found(cur):
+ name = f"not-found-{_uid()}"
+
+ with pytest.raises(ClientError) as e:
+ cur.untag_resource(ReportName=name, TagKeys=["kids"])
+
+ assert e.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert e.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_cur_untag_resource_nonexistent_keys(cur):
+ name = f"{name_prefix}-{_uid()}"
+ cur.put_report_definition(ReportDefinition=_report_definition(name))
+ cur.tag_resource(ReportName=name, Tags=test_tags)
+
+ # Untag keys that don't exist - should succeed gracefully.
+ resp = cur.untag_resource(ReportName=name, TagKeys=["nonexistent", "also-no"])
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+ # Original tags should still be there.
+ tags = cur.list_tags_for_resource(ReportName=name)["Tags"]
+ assert len(tags) == 2
+ assert all(tag in tags for tag in test_tags)
\ No newline at end of file