|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Stack lifecycle and validation, replayed from recordings of the live service. |
| 5 | +
|
| 6 | +Record against AWS with ``SMITHY_PYTHON_TEST_MODE=record pytest <this file>``. |
| 7 | +
|
| 8 | +The recordings are in ``recordings/<test function>/cloud_formation.py``. Each serves |
| 9 | +both clients, because playback answers by operation and never looks at the request. |
| 10 | +Stack names need a unique suffix, so a test compares only their prefix: the recording |
| 11 | +holds the name it was recorded with. |
| 12 | +""" |
| 13 | + |
| 14 | +import json |
| 15 | +import os |
| 16 | +from collections.abc import AsyncIterator |
| 17 | +from contextlib import AsyncExitStack |
| 18 | +from pathlib import Path |
| 19 | +from typing import cast |
| 20 | +from uuid import uuid4 |
| 21 | + |
| 22 | +import pytest |
| 23 | +from aws_sdk_cloudformation.aio.client import AsyncCloudFormationClient |
| 24 | +from aws_sdk_cloudformation.aio.config import AsyncCloudFormationConfig |
| 25 | +from aws_sdk_cloudformation.client import CloudFormationClient |
| 26 | +from aws_sdk_cloudformation.config import CloudFormationConfig |
| 27 | +from aws_sdk_cloudformation.models import Stack |
| 28 | +from dual_mode import MODES, AwaitableClient, Mode |
| 29 | +from smithy_test import instrument |
| 30 | +from smithy_test.aio import instrument_async |
| 31 | +from waiters import wait_until |
| 32 | + |
| 33 | +REGION = "us-west-2" |
| 34 | +RECORDING = os.environ.get("SMITHY_PYTHON_TEST_MODE") == "record" |
| 35 | +# Playback answers at once, so there is nothing to wait for. |
| 36 | +POLL_INTERVAL = 15 if RECORDING else 0 |
| 37 | + |
| 38 | +QUEUE_TEMPLATE = json.dumps( |
| 39 | + { |
| 40 | + "Description": "aws-sdk-python recorded test", |
| 41 | + "Parameters": {"Delay": {"Type": "Number", "Default": 0}}, |
| 42 | + "Resources": { |
| 43 | + "Queue": { |
| 44 | + "Type": "AWS::SQS::Queue", |
| 45 | + "Properties": {"DelaySeconds": {"Ref": "Delay"}}, |
| 46 | + } |
| 47 | + }, |
| 48 | + "Outputs": {"QueueUrl": {"Value": {"Ref": "Queue"}}}, |
| 49 | + } |
| 50 | +) |
| 51 | + |
| 52 | +# A fifo-suffixed name without FifoQueue=true is rejected by SQS during creation. |
| 53 | +FAILING_TEMPLATE = json.dumps( |
| 54 | + { |
| 55 | + "Resources": { |
| 56 | + "Queue": { |
| 57 | + "Type": "AWS::SQS::Queue", |
| 58 | + "Properties": {"QueueName": "aws-sdk-python-recorded-invalid.fifo"}, |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +) |
| 63 | + |
| 64 | + |
| 65 | +@pytest.fixture(params=MODES) |
| 66 | +def mode(request: pytest.FixtureRequest) -> Mode: |
| 67 | + return cast(Mode, request.param) |
| 68 | + |
| 69 | + |
| 70 | +@pytest.fixture |
| 71 | +async def cloudformation( |
| 72 | + mode: Mode, request: pytest.FixtureRequest |
| 73 | +) -> AsyncIterator[AsyncCloudFormationClient]: |
| 74 | + """A client in the test's mode, recorded or replayed per test function.""" |
| 75 | + name = cast(pytest.Function, request.node).originalname |
| 76 | + path = Path(__file__).parent / "recordings" / name / "cloud_formation.py" |
| 77 | + async with AsyncExitStack() as stack: |
| 78 | + if mode == "async": |
| 79 | + client = AsyncCloudFormationClient( |
| 80 | + await AsyncCloudFormationConfig.resolve(region=REGION) |
| 81 | + ) |
| 82 | + await stack.enter_async_context(client) |
| 83 | + await stack.enter_async_context(await instrument_async(client, path=path)) |
| 84 | + yield client |
| 85 | + else: |
| 86 | + sync = CloudFormationClient(CloudFormationConfig.resolve(region=REGION)) |
| 87 | + stack.enter_context(instrument(sync, path=path)) |
| 88 | + adapter = await stack.enter_async_context(AwaitableClient(sync)) |
| 89 | + yield cast(AsyncCloudFormationClient, adapter) |
| 90 | + |
| 91 | + |
| 92 | +async def test_create_describe_delete_stack( |
| 93 | + cloudformation: AsyncCloudFormationClient, |
| 94 | +) -> None: |
| 95 | + """A stack created with a parameter and tag reaches CREATE_COMPLETE with its outputs, then deletes.""" |
| 96 | + prefix = "aws-sdk-python-recorded-lifecycle" |
| 97 | + created = await cloudformation.create_stack( |
| 98 | + stack_name=f"{prefix}-{uuid4().hex[:8]}", |
| 99 | + template_body=QUEUE_TEMPLATE, |
| 100 | + parameters=[{"parameter_key": "Delay", "parameter_value": "1"}], |
| 101 | + tags=[{"key": "Purpose", "value": "RecordedTest"}], |
| 102 | + ) |
| 103 | + assert created.stack_id |
| 104 | + |
| 105 | + stack = await _wait_for_status(cloudformation, created.stack_id, "CREATE_COMPLETE") |
| 106 | + assert (stack.stack_name or "").startswith(prefix) |
| 107 | + assert stack.stack_id == created.stack_id |
| 108 | + assert [(p.parameter_key, p.parameter_value) for p in stack.parameters or []] == [ |
| 109 | + ("Delay", "1") |
| 110 | + ] |
| 111 | + assert [(t.key, t.value) for t in stack.tags or []] == [("Purpose", "RecordedTest")] |
| 112 | + outputs = {o.output_key: o.output_value for o in stack.outputs or []} |
| 113 | + assert (outputs["QueueUrl"] or "").startswith("https://sqs.") |
| 114 | + |
| 115 | + await cloudformation.delete_stack(stack_name=created.stack_id) |
| 116 | + # Deleted stacks stay describable by ID only. |
| 117 | + deleted = await _wait_for_status( |
| 118 | + cloudformation, created.stack_id, "DELETE_COMPLETE" |
| 119 | + ) |
| 120 | + assert deleted.deletion_time is not None |
| 121 | + |
| 122 | + |
| 123 | +async def test_failed_create_rolls_back_with_reason( |
| 124 | + cloudformation: AsyncCloudFormationClient, |
| 125 | +) -> None: |
| 126 | + """A stack whose resource fails to create rolls back and records the failure in its events.""" |
| 127 | + created = await cloudformation.create_stack( |
| 128 | + stack_name=f"aws-sdk-python-recorded-rollback-{uuid4().hex[:8]}", |
| 129 | + template_body=FAILING_TEMPLATE, |
| 130 | + ) |
| 131 | + assert created.stack_id |
| 132 | + try: |
| 133 | + await _wait_for_status(cloudformation, created.stack_id, "ROLLBACK_COMPLETE") |
| 134 | + |
| 135 | + events = await cloudformation.describe_stack_events(stack_name=created.stack_id) |
| 136 | + failures = [ |
| 137 | + e |
| 138 | + for e in events.stack_events or [] |
| 139 | + if e.resource_status == "CREATE_FAILED" and e.logical_resource_id == "Queue" |
| 140 | + ] |
| 141 | + assert failures |
| 142 | + assert failures[0].resource_status_reason |
| 143 | + finally: |
| 144 | + await cloudformation.delete_stack(stack_name=created.stack_id) |
| 145 | + await _wait_for_status(cloudformation, created.stack_id, "DELETE_COMPLETE") |
| 146 | + |
| 147 | + |
| 148 | +async def test_validate_template_reports_parameters_and_description( |
| 149 | + cloudformation: AsyncCloudFormationClient, |
| 150 | +) -> None: |
| 151 | + """ValidateTemplate returns the template's description and parameter declarations.""" |
| 152 | + result = await cloudformation.validate_template(template_body=QUEUE_TEMPLATE) |
| 153 | + assert result.description == "aws-sdk-python recorded test" |
| 154 | + assert [(p.parameter_key, p.default_value) for p in result.parameters or []] == [ |
| 155 | + ("Delay", "0") |
| 156 | + ] |
| 157 | + |
| 158 | + |
| 159 | +async def _wait_for_status( |
| 160 | + client: AsyncCloudFormationClient, stack_id: str, target: str |
| 161 | +) -> Stack: |
| 162 | + """Wait for the stack to reach ``target``, failing at once on any other settled status.""" |
| 163 | + |
| 164 | + async def describe() -> Stack: |
| 165 | + output = await client.describe_stacks(stack_name=stack_id) |
| 166 | + assert output.stacks |
| 167 | + return output.stacks[0] |
| 168 | + |
| 169 | + def reached_target(stack: Stack) -> bool: |
| 170 | + status = stack.stack_status or "" |
| 171 | + if status == target: |
| 172 | + return True |
| 173 | + assert status.endswith("_IN_PROGRESS"), ( |
| 174 | + f"stack reached {status}: {stack.stack_status_reason}" |
| 175 | + ) |
| 176 | + return False |
| 177 | + |
| 178 | + return await wait_until( |
| 179 | + describe, reached_target, interval=POLL_INTERVAL, timeout=600 |
| 180 | + ) |
0 commit comments