def test_update_termination_protection(self) -> None: """Test update_termination_protection.""" stack_name = "fake-stack" test_cases = [ MutableMap(aws=False, defined=True, expected=True), MutableMap(aws=True, defined=False, expected=False), MutableMap(aws=True, defined=True, expected=None), MutableMap(aws=False, defined=False, expected=None), ] for test in test_cases: self.stubber.add_response( "describe_stacks", { "Stacks": [ generate_describe_stacks_stack( stack_name, termination_protection=test["aws"] ) ] }, {"StackName": stack_name}, ) if isinstance(test["expected"], bool): self.stubber.add_response( "update_termination_protection", {"StackId": stack_name}, { "EnableTerminationProtection": test["expected"], "StackName": stack_name, }, ) with self.stubber: self.provider.update_termination_protection(stack_name, test["defined"]) self.stubber.assert_no_pending_responses()
def __init__( self, *, config_path: Optional[Path] = None, config: Optional[CfnginConfig] = None, deploy_environment: Optional[DeployEnvironment] = None, parameters: Optional[MutableMapping[str, Any]] = None, force_stacks: Optional[List[str]] = None, region: Optional[str] = "us-east-1", stack_names: Optional[List[str]] = None, **_: Any, ) -> None: """Instantiate class.""" self._boto3_test_client = MutableMap() self._boto3_test_stubber = MutableMap() # used during init process self.s3_stubber = self.add_stubber("s3", region=region) super().__init__( config_path=config_path, config=config, deploy_environment=deploy_environment, force_stacks=force_stacks, parameters=parameters, stack_names=stack_names, )
def __init__( self, *, command: Optional[str] = None, deploy_environment: Any = None, **_: Any ) -> None: """Instantiate class.""" if not deploy_environment: deploy_environment = DeployEnvironment(environ={}, explicit_name="test") super().__init__(command=command, deploy_environment=deploy_environment) self._boto3_test_client = MutableMap() self._boto3_test_stubber = MutableMap() self._use_concurrent = True
def test_find_default(self) -> None: """Validate default value functionality.""" mute_map = MutableMap(**VALUE) assert (mute_map.find( "NOT_VALID", "default_val") == "default_val"), "default should be used" assert (mute_map.find( "str_val", "default_val") == VALUE["str_val"]), "default should be ignored"
def test_delete(self) -> None: """Validate that keys can be deleted. Uses dot and bracket notation. Also tests `get` method. """ mute_map = MutableMap(**VALUE) del mute_map["str_val"] del mute_map["dict_val"] assert not mute_map.get("str_val") assert not mute_map.get("dict_val")
def __init__( self, *, clients: Optional[MutableMap] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, profile_name: Optional[str] = None, region_name: Optional[str] = None, ): """Instantiate class. Args: clients: Clients that have already been stubbed. aws_access_key_id: Same as boto3.Session. aws_secret_access_key: Same as boto3.Session. aws_session_token: Same as boto3.Session. profile_name: Same as boto3.Session. region_name: Same as boto3.Session. """ self._clients = clients or MutableMap() self._client_calls: Dict[str, Any] = {} self._session = MagicMock() self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.aws_session_token = aws_session_token self.profile_name = profile_name self.region_name = region_name
def test_bool(self) -> None: """Validates the bool value. Also tests setting an attr using bracket notation. """ mute_map = MutableMap() assert not mute_map mute_map["str_val"] = "test" assert mute_map
def __init__(self, **kwargs: Any) -> None: """Instantiate class.""" super().__init__() self._kwargs = kwargs self.deployments = [] self.future = MagicMock() self.tests = [] self.ignore_git_branch = False self.runway_version = SpecifierSet(">=1.10", prereleases=True) self.variables = MutableMap() # classmethods self.find_config_file = MagicMock( name="find_config_file", return_value="./runway.yml" ) self.load_from_file = MagicMock(name="load_from_file", return_value=self)
def test_find(self) -> None: """Validate the `find` method with and without `ignore_cache`. Also tests the `clear_found_cache` method and setting an attr value using dot notation. """ mute_map = MutableMap(**VALUE) assert mute_map.find("str_val") == VALUE["str_val"] mute_map["str_val"] = "new_val" assert mute_map.find("str_val") == VALUE["str_val"] assert mute_map.find("str_val", ignore_cache=True) == "new_val" mute_map.clear_found_cache() assert mute_map.find("str_val") == "new_val"
def test_format_results(self) -> None: """Test format_results.""" test_dict = { "nested": { "bool": True, "nested_key": "nested_value" }, "test_key": "test_value", } mute_map = MutableMap(**test_dict.copy()) assert LookupHandler.format_results(test_dict) == test_dict assert LookupHandler.format_results(mute_map) == test_dict assert (LookupHandler.format_results( test_dict, get="test_key") == test_dict["test_key"]) assert (LookupHandler.format_results( mute_map, get="test_key") == mute_map["test_key"]) assert (LookupHandler.format_results( mute_map, get="nested") == mute_map["nested"].data) assert (LookupHandler.format_results( mute_map, get="nested.nested_key") == mute_map["nested"]["nested_key"]) assert LookupHandler.format_results(mute_map, get="nested.bool") assert LookupHandler.format_results(mute_map, transform="str") == json.dumps( json.dumps(test_dict, indent=0)) assert LookupHandler.format_results(mute_map, transform="str", indent=2) == json.dumps( json.dumps(test_dict, indent=2)) assert (LookupHandler.format_results(mute_map, get="nested.bool", transform="str") == '"True"') with pytest.raises(TypeError): LookupHandler.format_results(["something"], get="key")
from runway.lookups.handlers.env import EnvLookup from runway.lookups.registry import ( RUNWAY_LOOKUP_HANDLERS, register_lookup_handler, unregister_lookup_handler, ) from runway.utils import MutableMap if TYPE_CHECKING: from pytest_mock import MockerFixture from ..factories import MockRunwayContext VALUES = {"str_val": "test"} CONTEXT = MutableMap(**{"env_vars": VALUES}) VARIABLES = MutableMap(**VALUES) def test_autoloaded_lookup_handlers(mocker: MockerFixture) -> None: """Test autoloaded lookup handlers.""" mocker.patch.dict(RUNWAY_LOOKUP_HANDLERS, {}) handlers = ["cfn", "ecr", "env", "ssm", "var"] for handler in handlers: assert (handler in RUNWAY_LOOKUP_HANDLERS ), f'Lookup handler: "{handler}" not registered' assert len(RUNWAY_LOOKUP_HANDLERS) == len( handlers ), f"expected {len(handlers)} autoloaded handlers but found {len(RUNWAY_LOOKUP_HANDLERS)}"
from mypy_boto3_acm.type_defs import DomainValidationTypeDef, ResourceRecordTypeDef from mypy_boto3_cloudformation.type_defs import StackResourceTypeDef from mypy_boto3_route53.type_defs import ( ChangeInfoTypeDef, ChangeResourceRecordSetsResponseTypeDef, ChangeTypeDef, ResourceRecordSetTypeDef, ) from pytest import MonkeyPatch from ...factories import MockCFNginContext STATUS = MutableMap( **{ "failed": FAILED, "new": SubmittedStatus("creating new stack"), "no": NO_CHANGE, "recreate": SubmittedStatus("destroying stack for re-creation"), "update": SubmittedStatus("updating existing stack"), }) def check_bool_is_true(val: Any) -> bool: """Check if a value is a true bool.""" if val and isinstance(val, bool): return True raise ValueError('Value should be "True"; got {}'.format(val)) def check_bool_is_false(val: Any) -> bool: """Check if a value is a false bool.""" if not val and isinstance(val, bool):
def test_data(self) -> None: """Validate the init process and retrieving sanitized data.""" mute_map = MutableMap(**VALUE) assert mute_map.data == VALUE
def test_uri(self, mock_image: MagicMock) -> None: """Test URI.""" assert DockerImage(image=mock_image).uri == MutableMap( latest=MOCK_IMAGE_REPO + ":latest", oldest=MOCK_IMAGE_REPO + ":oldest" )
"""Tests for lookup handler for var.""" # pylint: disable=no-self-use,unused-argument # pyright: basic from __future__ import annotations from typing import TYPE_CHECKING import pytest from runway.lookups.handlers.var import VarLookup from runway.utils import MutableMap if TYPE_CHECKING: from ...factories import MockRunwayContext VARIABLES = MutableMap(**{"str_val": "test", "false_val": False}) class TestVarLookup: """Tests for VarLookup.""" def test_handle(self, runway_context: MockRunwayContext) -> None: """Validate handle base functionality.""" assert ( VarLookup.handle("str_val", context=runway_context, variables=VARIABLES) == "test" ) def test_handle_false_result(self, runway_context: MockRunwayContext) -> None: """Validate that a bool value of False can be resolved.""" assert not VarLookup.handle(