Best Python code snippet using localstack_python
server.py
Source: server.py
...7from pprint import pprint8import boto39sts = boto3.client('sts')10accounts_by_number = {}11def assume_role_with_saml(saml_response: str, role_arn: str, principal_name: str) -> Path:12 account_number = re.search(r'(\d+)', role_arn).group(0)13 response = sts.assume_role_with_saml(14 RoleArn=role_arn,15 PrincipalArn='arn:aws:iam::{account}:saml-provider/{PrincipalName}'.format(16 account=account_number, PrincipalName=principal_name17 ),18 SAMLAssertion=saml_response,19 DurationSeconds=3600 * 1220 )21 pprint(response)22 credentials = response['Credentials']23 credentials_ini = (pathlib.Path.home() / '.aws' / 'credentials')24 cp = ConfigParser()25 cp.read(credentials_ini)26 account_name = accounts_by_number.get(account_number, account_number)27 for section in {'default', account_name}:28 cp.remove_section(section)29 cp.add_section(section)30 cp.set(section, 'aws_access_key_id', credentials['AccessKeyId'])31 cp.set(section, 'aws_secret_access_key', credentials['SecretAccessKey'])32 cp.set(section, 'aws_session_token', credentials['SessionToken'])33 with open(credentials_ini, mode='w') as fo:34 cp.write(fo)35 return credentials_ini36class MyHttpRequestHandler(SimpleHTTPRequestHandler):37 principal_name: str38 def do_POST(self):39 content_length = int(self.headers['Content-Length'])40 request_body = self.rfile.read(content_length).decode('utf-8')41 print(request_body)42 request_dict = json.loads(request_body)43 pprint(request_dict)44 if self.path == '/saml':45 status = 20046 try:47 credentials_ini = assume_role_with_saml(48 request_dict['SAMLResponse'], request_dict['roleARN'], self.principal_name49 )50 body = {'credentials_ini': str(credentials_ini)}51 except Exception as e:52 status = 40053 body = {'error': str(e)}54 self.send_response(status)55 self.send_header('Access-Control-Allow-Origin', '*')56 self.send_header('Content-type', 'application/json')57 self.end_headers()58 self.wfile.write(bytes(json.dumps(body), encoding='utf8'))59 else:60 self.send_error(404, self.path)61def run(identity_provider_name: str):...
conftest.py
Source: conftest.py
1from datetime import datetime, timedelta2import copy3import logging4import mock5import pytest6from dateutil.tz import tzlocal7from tests import create_assertion8@pytest.fixture9def mock_botocore_client():10 return mock.Mock()11@pytest.fixture12def client_creator(mock_botocore_client):13 # Create a mock sts client that returns a specific response14 # for assume_role_with_saml.15 expiration = datetime.now(tzlocal()) + timedelta(days=1)16 mock_botocore_client.assume_role_with_saml.return_value = {17 'Credentials': {18 'AccessKeyId': 'foo',19 'SecretAccessKey': 'bar',20 'SessionToken': 'baz',21 'Expiration': expiration22 },23 }24 return mock.Mock(return_value=mock_botocore_client)25@pytest.fixture26def prompter():27 return mock.Mock(return_value='mypassword')28@pytest.fixture29def login_form():30 return (31 '<html>'32 '<form action="login">'33 '<input name="username"/>'34 '<input name="password"/>'35 '</form>'36 '</html>'37 )38@pytest.fixture(params=[39 {'reversed': False},40 {'reversed': True}41])42def assertion(request):43 provider_arn = 'arn:aws:iam::123456789012:saml-provider/Example'44 role_arn = 'arn:aws:iam::123456789012:role/monty'45 is_reversed = request.param.get('reversed', False)46 if not is_reversed:47 config_string = '%s,%s' % (provider_arn, role_arn)48 else:49 config_string = '%s,%s' % (role_arn, provider_arn)50 return create_assertion([config_string])51@pytest.fixture(autouse=True)52def reset_logger():53 """Makes sure that mutations to the logger don't persist between tests."""54 logger = logging.getLogger('awsprocesscreds')55 original_level = logger.level56 original_handlers = copy.copy(logger.handlers)57 original_filters = copy.copy(logger.filters)58 # Everything after the yield will be called during test cleanup.59 yield60 logger.setLevel(original_level)61 for handler in logger.handlers:62 if handler not in original_handlers:63 logger.removeHandler(handler)64 for log_filter in logger.filters:65 if log_filter not in original_filters:66 logger.removeFilter(log_filter)67@pytest.fixture68def cache_dir(tmpdir):69 cache_directory = tmpdir.mkdir('awscreds-saml-cache')...
__main__.py
Source: __main__.py
1#2# Copyright 2019 - binx.io B.V.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15#16import logging17import click18from auth0_login import fatal19from auth0_login.aws import assume_role_with_saml20from auth0_login.config import setting21from auth0_login.saml import get_saml_token22@click.group(name='saml-login', help="A command line utility to obtain SAML tokens and AWS credentials.")23@click.option('--verbose', is_flag=True, default=False, help=' for tracing purposes')24@click.option('--configuration', '-c', default="DEFAULT", help='configured in .saml-login to use')25def cli(verbose, configuration):26 logging.basicConfig(format='%(levelname)s:%(message)s', level=(logging.DEBUG if verbose else logging.INFO))27 setting.filename = '.saml-login'28 setting.SECTION = configuration29 if not setting.exists:30 fatal('no configuration %s found in %s', configuration, setting.filename)31cli.add_command(get_saml_token)32cli.add_command(assume_role_with_saml)33if __name__ == '__main__':...
Check out the latest blogs from LambdaTest on this topic:
The fact is not alien to us anymore that cross browser testing is imperative to enhance your application’s user experience. Enhanced knowledge of popular and highly acclaimed testing frameworks goes a long way in developing a new app. It holds more significance if you are a full-stack developer or expert programmer.
QA testers have a unique role and responsibility to serve the customer. Serving the customer in software testing means protecting customers from application defects, failures, and perceived failures from missing or misunderstood requirements. Testing for known requirements based on documentation or discussion is the core of the testing profession. One unique way QA testers can both differentiate themselves and be innovative occurs when senseshaping is used to improve the application user experience.
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.
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!!