Best Python code snippet using localstack_python
test_aws.py
Source:test_aws.py  
...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="")...test_token_auth.py
Source:test_token_auth.py  
...23            "GratefulDeadConcerts", "admin", "admin", pyorient.DB_TYPE_GRAPH, ""24        )25        record = self.client.query( 'select from V limit 2' )26        assert isinstance( record[0], pyorient.otypes.OrientRecord )27        old_token = self.client.get_session_token()28        assert self.client.get_session_token() not in [29            None, '', b'', True, False30        ]31    def testReconnection(self):32        self.client = pyorient.OrientDB("localhost", 2424)33        assert self.client.get_session_token() == b''34        global old_token35        self.client.set_session_token( old_token )36        record = self.client.query( 'select from V limit 2' )37        assert isinstance( record[0], pyorient.otypes.OrientRecord )38    def testReconnectionFailRoot(self):39        assert self.client.get_session_token() == b''40        global old_token41        self.client.set_session_token( old_token )42        #43        # //this because the connection credentials44        # // are not correct for Orient root access45        with self.assertRaises( Exception ):46            self.client.db_exists( "GratefulDeadConcerts" )47    def testReconnectionRoot(self):48        assert self.client.get_session_token() == b''49        global old_token50        self.client.set_session_token( old_token )51        self.client.connect("root", "root")52        self.assertNotEquals( old_token, self.client.get_session_token() )53        res = self.client.db_exists( "GratefulDeadConcerts" )54        self.assertTrue( res )55    def testRenewAuthToken(self):56        assert self.client.get_session_token() == b''57        client = pyorient.OrientDB("localhost", 2424)58        client.set_session_token( True )59        client.db_open( "GratefulDeadConcerts", "admin", "admin" )60        res1 = client.record_load("#9:1")61        actual_token = client.get_session_token()62        del client63        #  create a new client64        client = pyorient.OrientDB("localhost", 2424)65        client.set_session_token( actual_token )66        res3 = client.record_load("#9:1")67        self.assertEqual(68            res1.oRecordData['name'],69            res3.oRecordData['name']70        )71        self.assertEqual(72            res1.oRecordData['out_sung_by'].get_hash(),73            res3.oRecordData['out_sung_by'].get_hash()74        )75        self.assertEqual(76            res1.oRecordData['out_written_by'].get_hash(),77            res3.oRecordData['out_written_by'].get_hash()78        )79        # set the flag again to true if you want to renew the token80        # client = pyorient.OrientDB("localhost", 2424)81        client.set_session_token( True )82        client.db_open( "GratefulDeadConcerts", "admin", "admin" )83        global old_token84        self.assertNotEqual( old_token, actual_token )85        self.assertNotEqual( old_token, client.get_session_token() )...aws.py
Source:aws.py  
...42    except KeyError as ex:43        raise CannotResolveError(f'"get_user" did not return key {ex}.')44    except Exception as ex:45        raise CannotResolveError(f'"get_user" failed: {ex}')46def get_session_token(47    logger: Logger,48    duration: int,49    serial: str,50    token: str,51) -> Tuple[Tuple[str, str, str], datetime]:52    """53    Attempts to get a session token for the current identity with the given54    MFA token.55    Returns a tuple holding the access key, secret key and session token, and56    the credentials' expiration date.57    """58    sts = client("sts")59    logger.debug("Requesting session token...")60    try:61        response = sts.get_session_token(62            DurationSeconds=duration,63            SerialNumber=serial,64            TokenCode=token,65        )66    except Exception as ex:67        raise CannotResolveError(f'"get_session_token" failed: {ex}')68    credentials = response.get("Credentials", None)69    if credentials is None:70        raise CannotResolveError(71            f'"get_session_token" did not return "Credentials": {response}'72        )73    return (74        (75            get_credential_str(credentials, "AccessKeyId"),...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!!
