Best Python code snippet using localstack_python
test_stack_set.py
Source:test_stack_set.py  
1import pytest2import json3from botocore.exceptions import ClientError4from uuid import uuid45from formica import cli, stack_set6from tests.unit.constants import STACK, CLOUDFORMATION_PARAMETERS, CLOUDFORMATION_TAGS7from tests.unit.constants import TEMPLATE, EC2_REGIONS, ACCOUNTS, ACCOUNT_ID, OPERATION_ID8from path import Path9@pytest.fixture10def logger(mocker):11    return mocker.patch('formica.stack_set.logger')12@pytest.fixture13def client(aws_client, paginators):14    aws_client.create_stack_instances.return_value = {'OperationId': OPERATION_ID}15    aws_client.delete_stack_instances.return_value = {'OperationId': OPERATION_ID}16    aws_client.update_stack_set.return_value = {'OperationId': OPERATION_ID}17    aws_client.get_paginator.side_effect = paginators(list_stack_instances=[], list_accounts=[ACCOUNTS])18    exception = ClientError(19        dict(Error={'Code': 'StackSetNotFoundException'}), "DescribeStackSet")20    aws_client.describe_stack_set.side_effect = exception21    return aws_client22@pytest.fixture23def loader(mocker):24    mock = mocker.patch('formica.loader.Loader')25    mock.return_value.template.return_value = TEMPLATE26    return mock27@pytest.fixture28def template(client, mocker):29    template = mocker.Mock()30    client.describe_stack_set.return_value = {'StackSet': {'TemplateBody': template}}31    return template32@pytest.fixture33def compare(mocker):34    return mocker.patch('formica.stack_set.compare_stack_set')35@pytest.fixture36def input(mocker):37    input_mock = mocker.patch('formica.stack_set.input')38    input_mock.return_value = 'yes'39    return input_mock40@pytest.fixture41def time(mocker):42    return mocker.patch('formica.stack_set.time')43@pytest.fixture44def wait(mocker):45    return mocker.patch('formica.stack_set.wait_for_stack_set_operation')46def dump_template(template):47    return json.dumps(template, indent=None, sort_keys=True, separators=(',', ':'))48def test_create_stack_set(client, logger, loader):49    cli.main([50        'stack-set',51        'create',52        '--stack-set', STACK,53        '--parameters', 'P1=PV1', 'P2=PV2',54        '--tags', 'T1=TV1', 'T2=TV2',55        '--capabilities', 'CAPABILITY_IAM',56        '--execution-role-name', 'ExecutionRole',57        '--administration-role-arn', 'AdministrationRole',58    ])59    client.create_stack_set.assert_called_with(60        StackSetName=STACK,61        TemplateBody=TEMPLATE,62        Parameters=CLOUDFORMATION_PARAMETERS,63        Tags=CLOUDFORMATION_TAGS,64        Capabilities=['CAPABILITY_IAM'],65        ExecutionRoleName='ExecutionRole',66        AdministrationRoleARN='AdministrationRole'67    )68def test_create_stack_set_with_administration_name(client, logger, loader):69    client.get_caller_identity.return_value = {'Account': ACCOUNT_ID}70    cli.main([71        'stack-set',72        'create',73        '--stack-set', STACK,74        '--administration-role-name', 'AdministrationRole',75    ])76    client.create_stack_set.assert_called_with(77        StackSetName=STACK,78        TemplateBody=TEMPLATE,79        AdministrationRoleARN='arn:aws:iam::1234567890:role/AdministrationRole'80    )81def test_create_stack_set_without_arguments(client, logger, loader):82    cli.main([83        'stack-set',84        'create',85        '--stack-set', STACK86    ])87    client.create_stack_set.assert_called_with(88        StackSetName=STACK,89        TemplateBody=TEMPLATE90    )91def test_create_stack_set_with_main_account(boto_client, client, logger, tmpdir):92    accountid = str(uuid4())93    client.get_caller_identity.return_value = {'Account': accountid}94    with Path(tmpdir):95        with open('test.template.json', 'w') as f:96            f.write('')97        cli.main([98            'stack-set',99            'create',100            '--stack-set', STACK,101            '--main-account-parameter'102        ])103    boto_client.assert_called_with('sts')104    client.create_stack_set.assert_called_with(105        StackSetName=STACK,106        TemplateBody=dump_template({'Parameters': {'MainAccount': {'Type': 'String', 'Default': accountid}}})107    )108def test_create_stack_set_with_main_account_and_existing_parameters(session, client, logger, tmpdir):109    accountid = str(uuid4())110    client.get_caller_identity.return_value = {'Account': accountid}111    with Path(tmpdir):112        with open('test.template.json', 'w') as f:113            f.write(json.dumps({'Parameters': {'SomeParam': {'Type': 'String'}}}))114        cli.main([115            'stack-set',116            'create',117            '--stack-set', STACK,118            '--main-account-parameter',119            '--parameters', 'A=B'120        ])121    client.create_stack_set.assert_called_with(122        StackSetName=STACK,123        TemplateBody=dump_template(124            {'Parameters': {'SomeParam': {'Type': 'String'}, 'MainAccount': {'Type': 'String', 'Default': accountid}}}),125        Parameters=[{'ParameterKey': 'A', 'ParameterValue': 'B', 'UsePreviousValue': False}]126    )127def test_do_not_create_if_existing(session, logger, tmpdir, mocker):128    client = mocker.Mock()129    session.return_value.client.return_value = client130    accountid = str(uuid4())131    client.get_caller_identity.return_value = {'Account': accountid}132    client.describe_stack_set().return_value = {}133    with Path(tmpdir):134        with open('test.template.json', 'w') as f:135            f.write(json.dumps({'Parameters': {'SomeParam': {'Type': 'String'}}}))136        cli.main([137            'stack-set',138            'create',139            '--stack-set', STACK,140        ])141    client.create_stack_set.assert_not_called()142def test_update_stack_set_with_compare_check(client, loader, input, compare, wait):143    client.describe_stack_set_operation.return_value = {'StackSetOperation': {'Status': 'SUCCEEDED'}}144    cli.main([145        'stack-set',146        'update',147        '--stack-set', STACK,148        '--parameters', 'P1=PV1', 'P2=PV2',149        '--tags', 'T1=TV1', 'T2=TV2',150        '--vars', 'V1=VV1',151        '--capabilities', 'CAPABILITY_IAM',152        '--execution-role-name', 'ExecutionRole',153        '--administration-role-arn', 'AdministrationRole',154        '--accounts', '123456789', '987654321',155        '--regions', 'eu-central-1', 'eu-west-1',156        '--region-order', 'eu-central-1', 'eu-west-1',157        '--failure-tolerance-count', '1',158        '--max-concurrent-count', '1'159    ])160    client.update_stack_set.assert_called_with(161        StackSetName=STACK,162        TemplateBody=TEMPLATE,163        Parameters=CLOUDFORMATION_PARAMETERS,164        Tags=CLOUDFORMATION_TAGS,165        Capabilities=['CAPABILITY_IAM'],166        ExecutionRoleName='ExecutionRole',167        AdministrationRoleARN='AdministrationRole',168        Accounts=['123456789', '987654321'],169        Regions=['eu-central-1', 'eu-west-1'],170        OperationPreferences={171            'RegionOrder': ['eu-central-1', 'eu-west-1'],172            'FailureToleranceCount': 1,173            'MaxConcurrentCount': 1174        }175    )176    input.assert_called_once()177    wait.assert_called_with(STACK, OPERATION_ID)178def test_update_stack_set_yes_ignores_input(client, loader, input, compare, wait):179    client.describe_stack_set_operation.return_value = {'StackSetOperation': {'Status': 'SUCCEEDED'}}180    cli.main([181        'stack-set',182        'update',183        '--stack-set', STACK,184        '--yes'185    ])186    client.update_stack_set.assert_called_with(187        StackSetName=STACK,188        TemplateBody=TEMPLATE189    )190    input.assert_not_called()191def test_update_stack_set_with_main_account(boto_client, client, logger, tmpdir, input, compare, wait):192    client.update_stack_set.return_value = {'OperationId': '12345'}193    accountid = str(uuid4())194    client.get_caller_identity.return_value = {'Account': accountid}195    with Path(tmpdir):196        with open('test.template.json', 'w') as f:197            f.write('')198        cli.main([199            'stack-set',200            'update',201            '--stack-set', STACK,202            '--main-account-parameter'203        ])204    boto_client.assert_any_call('sts')205    boto_client.assert_any_call('cloudformation')206    client.update_stack_set.assert_called_with(207        StackSetName=STACK,208        TemplateBody=dump_template({'Parameters': {'MainAccount': {'Type': 'String', 'Default': accountid}}})209    )210def test_update_stack_set_with_all_regions_and_accounts(client, logger, loader, input, compare, wait):211    client.get_caller_identity.return_value = {'Account': '5678'}212    client.describe_regions.return_value = EC2_REGIONS213    cli.main([214        'stack-set',215        'update',216        '--stack-set', STACK,217        '--all-regions',218        '--all-accounts'219    ])220    client.update_stack_set.assert_called_with(221        StackSetName=STACK,222        TemplateBody=TEMPLATE,223        Accounts=['1234', '5678'],224        Regions=['us-west-1', 'us-west-2']225    )226def test_update_stack_set_with_all_subaccounts(client, logger, loader, input, compare, wait):227    client.update_stack_set.return_value = {'OperationId': '12345'}228    client.get_caller_identity.return_value = {'Account': '5678'}229    client.describe_regions.return_value = EC2_REGIONS230    cli.main([231        'stack-set',232        'update',233        '--stack-set', STACK,234        '--all-subaccounts'235    ])236    client.update_stack_set.assert_called_with(237        StackSetName=STACK,238        TemplateBody=TEMPLATE,239        Accounts=['1234']240    )241def test_update_stack_set_with_excluded_accounts(client, logger, loader, input, compare, wait):242    client.update_stack_set.return_value = {'OperationId': '12345'}243    client.get_caller_identity.return_value = {'Account': '5678'}244    client.describe_regions.return_value = EC2_REGIONS245    cli.main([246        'stack-set',247        'add-instances',248        '--stack-set', STACK,249        '--excluded-accounts', '1234',250        '--regions', 'eu-central-1'251    ])252    client.create_stack_instances.assert_called_with(253        StackSetName=STACK,254        Accounts=['5678'],255        Regions=['eu-central-1']256    )257def test_update_with_create_missing(client, logger, loader, input, compare, wait):258    client.update_stack_set.return_value = {'OperationId': '12345'}259    client.get_caller_identity.return_value = {'Account': '5678'}260    client.describe_regions.return_value = EC2_REGIONS261    cli.main([262        'stack-set',263        'update',264        '--stack-set', STACK,265        '--all-subaccounts',266        '--create-missing'267    ])268    client.create_stack_set.assert_called_with(269        StackSetName=STACK,270        TemplateBody=TEMPLATE271    )272    client.describe_stack_set.assert_called_with(StackSetName=STACK)273def test_add_stack_set_instances(client, loader, wait, input):274    cli.main([275        'stack-set',276        'add-instances',277        '--stack-set', STACK,278        '--accounts', '123456789', '987654321',279        '--regions', 'eu-central-1', 'eu-west-1',280    ])281    client.create_stack_instances.assert_called_with(282        StackSetName=STACK,283        Accounts=['123456789', '987654321'],284        Regions=['eu-central-1', 'eu-west-1']285    )286    wait.assert_called_with(STACK, OPERATION_ID)287def test_stack_set_accounts_converts_to_string():288    assert stack_set.accounts({'accounts': ['123', 12345, 54321]}) == ['123', '12345', '54321']289def test_add_all_stack_set_instances(client, loader, wait, input):290    client.get_caller_identity.return_value = {'Account': '5678'}291    client.describe_regions.return_value = EC2_REGIONS292    cli.main([293        'stack-set',294        'add-instances',295        '--stack-set', STACK,296        '--all-accounts',297        '--all-regions',298    ])299    client.create_stack_instances.assert_called_with(300        StackSetName=STACK,301        Accounts=['1234', '5678'],302        Regions=['us-west-1', 'us-west-2']303    )304def test_add_stack_set_instances_with_operation_preferences(client, loader, wait, input):305    cli.main([306        'stack-set',307        'add-instances',308        '--accounts', '123456789', '987654321',309        '--regions', 'eu-central-1', 'eu-west-1',310        '--stack-set', STACK,311        '--max-concurrent-percentage', '1',312        '--failure-tolerance-percentage', '1',313    ])314    client.create_stack_instances.assert_called_with(315        StackSetName=STACK,316        Accounts=['123456789', '987654321'],317        Regions=['eu-central-1', 'eu-west-1'],318        OperationPreferences={319            'FailureTolerancePercentage': 1,320            'MaxConcurrentPercentage': 1321        }322    )323def test_add_only_missing_stack_set_instances(client, loader, wait, input, mocker, paginators):324    client.get_paginator.side_effect = paginators(list_stack_instances=[325        {'Summaries': [{'Account': '123456789', "Region": 'eu-central-1'}]}])326    cli.main([327        'stack-set',328        'add-instances',329        '--accounts', '123456789', '987654321',330        '--regions', 'eu-central-1', 'eu-west-1',331        '--stack-set', STACK332    ])333    assert client.create_stack_instances.mock_calls == [334        mocker.call(335            StackSetName=STACK,336            Accounts=['987654321'],337            Regions=['eu-central-1']338        ),339        mocker.call(340            StackSetName=STACK,341            Accounts=['123456789', '987654321'],342            Regions=['eu-west-1']343        )344    ]345def test_add_only_missing_stack_set_instances_with_one_call_if_possible(client, loader, wait, input, mocker,346                                                                        paginators):347    client.get_paginator.side_effect = paginators(list_stack_instances=[348        {'Summaries': [{'Account': '123456789', "Region": 'eu-central-1'},349                       {'Account': '987654321', "Region": 'eu-central-1'}]}])350    cli.main([351        'stack-set',352        'add-instances',353        '--accounts', '123456789', '987654321',354        '--regions', 'eu-central-1', 'eu-west-1',355        '--stack-set', STACK356    ])357    assert client.create_stack_instances.mock_calls == [358        mocker.call(359            StackSetName=STACK,360            Accounts=['123456789', '987654321'],361            Regions=['eu-west-1']362        )363    ]364    client.get_paginator.side_effect = paginators(list_stack_instances=[365        {'Summaries': [{'Account': '123456789', "Region": 'eu-central-1'},366                       {'Account': '123456789', "Region": 'eu-west-1'}]}])367    cli.main([368        'stack-set',369        'add-instances',370        '--accounts', '123456789', '987654321',371        '--regions', 'eu-central-1', 'eu-west-1',372        '--stack-set', STACK373    ])374    assert len(client.create_stack_instances.mock_calls) == 2375    client.create_stack_instances.assert_called_with(376        StackSetName=STACK,377        Accounts=['987654321'],378        Regions=['eu-central-1', 'eu-west-1']379    )380def test_remove_stack_set_instances(client, loader, wait, input):381    cli.main([382        'stack-set',383        'remove-instances',384        '--stack-set', STACK,385        '--accounts', '123456789', '987654321',386        '--regions', 'eu-central-1', 'eu-west-1',387        '--retain',388        '--region-order', 'eu-central-1', 'eu-west-1',389        '--max-concurrent-percentage', '1',390        '--failure-tolerance-percentage', '1',391    ])392    client.delete_stack_instances.assert_called_with(393        StackSetName=STACK,394        Accounts=['123456789', '987654321'],395        Regions=['eu-central-1', 'eu-west-1'],396        RetainStacks=True,397        OperationPreferences={398            'RegionOrder': ['eu-central-1', 'eu-west-1'],399            'FailureTolerancePercentage': 1,400            'MaxConcurrentPercentage': 1401        }402    )403    wait.assert_called_with(STACK, OPERATION_ID)404def test_remove_all_stack_set_instances(client, loader, wait, input):405    client.get_caller_identity.return_value = {'Account': '5678'}406    client.describe_regions.return_value = EC2_REGIONS407    cli.main([408        'stack-set',409        'remove-instances',410        '--stack-set', STACK,411        '--all-accounts',412        '--all-regions',413    ])414    client.delete_stack_instances.assert_called_with(415        StackSetName=STACK,416        Accounts=['1234', '5678'],417        Regions=['us-west-1', 'us-west-2'],418        RetainStacks=False419    )420def test_remove_stack_set(client, loader):421    cli.main([422        'stack-set',423        'remove',424        '--stack-set', STACK,425    ])426    client.delete_stack_set.assert_called_with(427        StackSetName=STACK428    )429def test_excluded_regions_with_preference(client, logger, loader, input, compare, wait):430    client.update_stack_set.return_value = {'OperationId': '12345'}431    client.get_caller_identity.return_value = {'Account': '5678'}432    client.describe_regions.return_value = EC2_REGIONS433    cli.main([434        'stack-set',435        'update',436        '--stack-set', STACK,437        '--all-accounts',438        '--excluded-regions',439        'us-west-1',440        '--all-regions'441    ])442    client.update_stack_set.assert_called_with(443        StackSetName=STACK,444        TemplateBody=TEMPLATE,445        Accounts=['1234', '5678'],446        Regions=['us-west-2']447    )448def test_main_account_only_deployment_with_preference(client, logger, loader, compare, input, wait):449    client.update_stack_set.return_value = {'OperationId': '12345'}450    client.describe_regions.return_value = EC2_REGIONS451    accountid = str(uuid4())452    client.get_caller_identity.return_value = {'Account': accountid}453    cli.main([454        'stack-set',455        'update',456        '--stack-set', STACK,457        '--main-account',458        '--all-accounts',459        '--excluded-regions',460        'us-west-1'461    ])462    client.update_stack_set.assert_called_with(463        StackSetName=STACK,464        TemplateBody=TEMPLATE,465        Accounts=[accountid],466        Regions=['us-west-2']467    )468def test_diff_cli_call(template, mocker, client, session):469    diff = mocker.patch('formica.diff.compare_stack_set')470    cli.main(['stack-set', 'diff', '--stack-set', STACK, '--main-account-parameter'])471    diff.assert_called_with(stack=STACK, parameters={}, vars={}, tags={}, main_account_parameter=True)472def test_diff_cli_call_with_vars(template, mocker, client, session):473    diff = mocker.patch('formica.diff.compare_stack_set')474    cli.main(['stack-set', 'diff', '--stack', STACK, '--vars', 'V=1', '--parameters', 'P=2', '--tags', 'T=3'])475    diff.assert_called_with(stack=STACK, vars={'V': '1'}, parameters={'P': '2'}, tags={'T': '3'},476                            main_account_parameter=False)477def test_stack_set_waiter(client, loader, compare, time):478    client.describe_stack_set_operation.side_effect = [{'StackSetOperation': {'Status': state}} for state in479                                                       ['RUNNING', 'SUCCEEDED']]480    cli.main([481        'stack-set',482        'update',483        '--stack-set', STACK,484        '--yes'485    ])486    client.update_stack_set.assert_called_with(487        StackSetName=STACK,488        TemplateBody=TEMPLATE489    )490    time.sleep.assert_called_with(5)491    assert time.sleep.call_count == 2492def test_stack_set_waiter_exits_on_failed_operation(client, loader, input, compare, time):493    client.describe_stack_set_operation.side_effect = [{'StackSetOperation': {'Status': state}} for state in494                                                       ['RUNNING', 'FAILED']]495    with pytest.raises(SystemExit, match='1'):496        cli.main([497            'stack-set',498            'update',499            '--stack-set', STACK,500            '--yes'501        ])502    client.update_stack_set.assert_called_with(503        StackSetName=STACK,504        TemplateBody=TEMPLATE505    )506    time.sleep.assert_called_with(5)...util_cfn.py
Source:util_cfn.py  
...92        raise Exception(erm)93def update_stackset_id_for_organization(ctx, stackSetName, reqd):94    try:95        cfn_client = ctx.client('cloudformation')96        cfn_client.update_stack_set(97            StackSetName=stackSetName,98            Description=reqd['Description'],99            TemplateBody=reqd['TemplateBody'],100            PermissionModel=reqd['PermissionModel'],101            AutoDeployment={102                'Enabled': reqd['AutoDeployment']['Enabled'],103                'RetainStacksOnAccountRemoval': reqd['AutoDeployment']['RetainStacksOnAccountRemoval']104            },105            Capabilities = reqd['Capabilities'],106            CallAs='DELEGATED_ADMIN'107        )108    except botocore.exceptions.ClientError as e:109        erm = _fail(e, 'update_stack_set', stackSetName)110        raise Exception(erm)...cloudformation.py
Source:cloudformation.py  
...30        summaries = self.client.list_stack_sets(31            Status=status32        )["Summaries"]33        return summaries34    def update_stack_set(self, stack_set_name, description, tags, parameters=None, capabilities=None, region_order=None):35        if parameters is None:36            parameters = []37        if capabilities is None:38            capabilities = []39        if region_order is None:40            region_order = []41        operation_id = self.client.update_stack_set(42            StackSetName=stack_set_name,43            Description=description,44            UsePreviousTemplate=True,45            Parameters=parameters,46            Capabilities=capabilities,47            Tags=tags,48            OperationPreferences={49                "RegionOrder": region_order,50                "FailureTolerancePercentage": 0,51                "MaxConcurrentPercentage": 10052            }53        )["OperationId"]54        return operation_id55    def create_stack_instances(self, stack_set_name, accounts, regions, parameter_overrides=None, region_order=None):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
