How to use list_mfa_devices method in localstack

Best Python code snippet using localstack_python

test_aws.py

Source:test_aws.py Github

copy

Full Screen

1from datetime import datetime2from logging import Logger3from mock import Mock, patch4from pytest import mark, raises5from wev.sdk.exceptions import CannotResolveError6from wev_awsmfa.aws import (7 discover_mfa_device_arn,8 discover_user_name,9 get_session_token,10)11def test_discover_mfa_device_arn(logger: Logger) -> None:12 response = {"MFADevices": [{"SerialNumber": "foo"}]}13 with patch("wev_awsmfa.aws.client") as client_maker:14 client = Mock()15 client.list_mfa_devices = Mock(return_value=response)16 client_maker.return_value = client17 assert discover_mfa_device_arn(logger=logger, username="bob") == "foo"18def test_discover_mfa_device_arn__exception(logger: Logger) -> None:19 with raises(CannotResolveError) as ex:20 with patch("wev_awsmfa.aws.client") as client_maker:21 client = Mock()22 client.list_mfa_devices = Mock(side_effect=Exception("puppers everywhere"))23 client_maker.return_value = client24 discover_mfa_device_arn(logger=logger, username="bob")25 assert str(ex.value) == '"list_mfa_devices" failed: puppers everywhere'26@mark.parametrize(27 "response, expect",28 [29 (30 {"foo": "bar"},31 "\"list_mfa_devices\" did not return \"MFADevices\": {'foo': 'bar'}",32 ),33 (34 {"MFADevices": []},35 "IAM user has no registered MFA devices.",36 ),37 (38 {"MFADevices": [{}, {}]},39 '"list_mfa_devices" returned multiple devices',40 ),41 (42 {"MFADevices": [{"foo": "bar"}]},43 (44 '"list_mfa_devices" returned a device without a serial number: '45 "{'foo': 'bar'}"46 ),47 ),48 ],49)50def test_discover_mfa_device_arn__invalid(51 response: dict, expect: str, logger: Logger52) -> None:53 with raises(CannotResolveError) as ex:54 with patch("wev_awsmfa.aws.client") as client_maker:55 client = Mock()56 client.list_mfa_devices = Mock(return_value=response)57 client_maker.return_value = client58 discover_mfa_device_arn(logger=logger, username="bob")59 assert str(ex.value) == expect60def test_discover_user_name(logger: Logger) -> None:61 with patch("wev_awsmfa.aws.client") as client_maker:62 client = Mock()63 client.get_user = Mock(return_value={"User": {"UserName": "bob"}})64 client_maker.return_value = client65 assert discover_user_name(logger=logger) == "bob"66def test_discover_user_name__exception(logger: Logger) -> None:67 with raises(CannotResolveError) as ex:68 with patch("wev_awsmfa.aws.client") as client_maker:69 client = Mock()70 client.get_user = Mock(side_effect=Exception("fish everywhere"))71 client_maker.return_value = client72 discover_user_name(logger=logger)73 assert str(ex.value) == '"get_user" failed: fish everywhere'74def test_discover_user_name__invalid(logger: Logger) -> None:75 with raises(CannotResolveError) as ex:76 with patch("wev_awsmfa.aws.client") as client_maker:77 client = Mock()78 client.get_user = Mock(return_value={})79 client_maker.return_value = client80 discover_user_name(logger=logger)81 assert str(ex.value) == "\"get_user\" did not return key 'User'."82def test_get_session_token(logger: Logger) -> None:83 response = {84 "Credentials": {85 "AccessKeyId": "alpha",86 "SecretAccessKey": "beta",87 "SessionToken": "gamma",88 "Expiration": datetime.fromisoformat("2020-01-01 00:00:00"),89 }90 }91 with patch("wev_awsmfa.aws.client") as client_maker:92 client = Mock()93 client.get_session_token = Mock(return_value=response)94 client_maker.return_value = client95 actual = get_session_token(logger=logger, duration=0, serial="", token="")96 assert actual == (97 ("alpha", "beta", "gamma"),98 datetime.fromisoformat("2020-01-01 00:00:00"),99 )100def test_get_session_token_exception(logger: Logger) -> None:101 with raises(CannotResolveError) as ex:102 with patch("wev_awsmfa.aws.client") as client_maker:103 client = Mock()104 client.get_session_token = Mock(side_effect=Exception("squids everywhere"))105 client_maker.return_value = client106 get_session_token(logger=logger, duration=0, serial="", token="")107 assert str(ex.value) == '"get_session_token" failed: squids everywhere'108@mark.parametrize(109 "response, expect",110 [111 (112 {"foo": "bar"},113 "\"get_session_token\" did not return \"Credentials\": {'foo': 'bar'}",114 ),115 (116 {"Credentials": {"foo": "bar"}},117 (118 '"get_session_token" returned credentials without '119 "\"AccessKeyId\": {'foo': 'bar'}"120 ),121 ),122 (123 {"Credentials": {"AccessKeyId": "alpha"}},124 (125 '"get_session_token" returned credentials without '126 "\"SecretAccessKey\": {'AccessKeyId': 'alpha'}"127 ),128 ),129 (130 {131 "Credentials": {132 "AccessKeyId": "alpha",133 "SecretAccessKey": "beta",134 "SessionToken": "gamma",135 }136 },137 (138 '"get_session_token" returned credentials without '139 "\"Expiration\": {'AccessKeyId': 'alpha', 'SecretAccessKey': "140 "'beta', 'SessionToken': 'gamma'}"141 ),142 ),143 (144 {145 "Credentials": {146 "AccessKeyId": "alpha",147 "SecretAccessKey": "beta",148 "SessionToken": "gamma",149 "Expiration": "delta",150 }151 },152 (153 '"get_session_token" did not return credential key '154 "\"Expiration\" as datetime: {'AccessKeyId': 'alpha', "155 "'SecretAccessKey': 'beta', 'SessionToken': 'gamma', "156 "'Expiration': 'delta'}"157 ),158 ),159 ],160)161def test_get_session_token__invalid(162 response: dict,163 expect: str,164 logger: Logger,165) -> None:166 with raises(CannotResolveError) as ex:167 with patch("wev_awsmfa.aws.client") as client_maker:168 client = Mock()169 client.get_session_token = Mock(return_value=response)170 client_maker.return_value = client171 get_session_token(logger=logger, duration=0, serial="", token="")...

Full Screen

Full Screen

aws.py

Source:aws.py Github

copy

Full Screen

...10 """11 logger.debug("Requesting MFA devices...")12 iam = client("iam")13 try:14 response = iam.list_mfa_devices(MaxItems=2, UserName=username)15 except Exception as ex:16 raise CannotResolveError(f'"list_mfa_devices" failed: {ex}')17 mfa_devices = response.get("MFADevices", None)18 if mfa_devices is None:19 raise CannotResolveError(20 f'"list_mfa_devices" did not return "MFADevices": {response}'21 )22 if len(mfa_devices) == 0:23 raise CannotResolveError("IAM user has no registered MFA devices.")24 if len(mfa_devices) > 1:25 raise CannotResolveError('"list_mfa_devices" returned multiple devices')26 mfa_device = mfa_devices[0]27 serial = mfa_device.get("SerialNumber", None)28 if not serial:...

Full Screen

Full Screen

awsmfautils_test.py

Source:awsmfautils_test.py Github

copy

Full Screen

1import blessclient.awsmfautils as awsmfautils2import os3import datetime4def test_unset_token():5 os.environ['AWS_ACCESS_KEY_ID'] = 'foo'6 os.environ['AWS_SESSION_TOKEN'] = 'foo'7 os.environ['AWS_SECURITY_TOKEN'] = 'foo'8 awsmfautils.unset_token()9 assert 'AWS_ACCESS_KEY_ID' not in os.environ10 assert 'AWS_SECRET_ACCESS_KEY' not in os.environ11 assert 'AWS_SESSION_TOKEN' not in os.environ12 assert 'AWS_SECURITY_TOKEN' not in os.environ13def test_get_serial(mock):14 list_mfa_devices = {15 u'MFADevices': [{16 u'UserName': 'foobar',17 u'SerialNumber': 'arn:aws:iam::000000000000:mfa/foobar',18 u'EnableDate': datetime.datetime.utcnow()19 }],20 u'IsTruncated': False,21 'ResponseMetadata': {22 'RetryAttempts': 0,23 'HTTPStatusCode': 200,24 'RequestId': '85d05b5b-d2ca-11e6-96b6-8503a2da6360',25 'HTTPHeaders': {26 'x-amzn-requestid': '85d05b5b-d2ca-11e6-96b6-8503a2da6360',27 'date': 'Wed, 04 Jan 2017 22:09:54 GMT',28 'content-length': '528',29 'content-type': 'text/xml'}30 }31 }32 iam_client = mock.Mock()33 iam_client.list_mfa_devices.return_value = list_mfa_devices34 serial = awsmfautils.get_serial(iam_client, 'foobar')35 iam_client.list_mfa_devices.assert_called_once_with(UserName='foobar')36 assert serial == 'arn:aws:iam::000000000000:mfa/foobar'37def test_get_role_arn():38 norole = awsmfautils.get_role_arn(39 'arn:aws:iam::000000000000:user/foobar', None)40 assert norole == ''41 rolebar = awsmfautils.get_role_arn(42 'arn:aws:iam::000000000000:user/foobar', 'rolebar')43 assert rolebar == 'arn:aws:iam::000000000000:role/rolebar'44 rolebar_acct = awsmfautils.get_role_arn(45 'arn:aws:iam::000000000000:user/foobar', 'rolebar', '111111111111')...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful