Best Python code snippet using localstack_python
lambda_function.py
Source:lambda_function.py
...55 })56 domain_name_arn = gen_apigateway_arn(domain_name, region)57 get_domain_name(prev_state, domain_name, desired_config, desired_tls_config, tags, region)58 create_domain_name(domain_name, desired_config, desired_tls_config, tags, region)59 update_domain_name(domain_name, desired_config, desired_tls_config, region)60 remove_tags(domain_name_arn)61 add_tags(domain_name_arn)62 #We call this one no matter what63 remove_domain_name()64 return eh.finish()65 except Exception as e:66 msg = traceback.format_exc()67 print(msg)68 eh.add_log("Unexpected Error", {"error": str(e)}, is_error=True)69 eh.declare_return(200, 0, error_code=str(e))70 return eh.finish()71def form_domain(subdomain, base_domain):72 if subdomain and base_domain:73 return f"{subdomain}.{base_domain}"74 else:75 return None76@ext(handler=eh, op="get_acm_cert")77def get_acm_cert(domain_name, region):78 cursor = 'none'79 certs = []80 while cursor:81 try:82 payload = remove_none_attributes({83 "CertificateStatuses": ["ISSUED"],84 "NextToken": cursor if cursor != 'none' else None85 })86 cert_response = acm.list_certificates(**payload)87 print(f"cert_response = {cert_response}")88 certs.extend(cert_response.get("CertificateSummaryList", []))89 cursor = cert_response.get("nextToken")90 except ClientError as e:91 handle_common_errors(e, eh, "List Certificates Failed", 0)92 93 # print(certs)94 print(list(filter(lambda x: domain_name.endswith(x["DomainName"].replace("*", "")), certs)))95 sorted_matching_certs = list(filter(lambda x: domain_name.endswith(x["DomainName"].replace("*", "")), certs))96 sorted_matching_certs.sort(key=lambda x:-len(x['DomainName']))97 print(f"sorted_matching_certs = {sorted_matching_certs}")98 if not sorted_matching_certs:99 eh.perm_error("No Matching ACM Certificate Found, Cannot Create API Custom Domain")100 eh.add_log("No Matching ACM Certificates", {"all_certs": certs}, is_error=True)101 return 0102 eh.add_op("get_domain_name")103 certificate_arn = sorted_matching_certs[0]['CertificateArn']104 certificate_domain_name = sorted_matching_certs[0]['DomainName']105 eh.add_props({"certificate_arn": certificate_arn,106 "certificate_domain_name": certificate_domain_name})107 eh.add_links({"ACM Certificate": gen_certificate_link(certificate_arn, region)})108@ext(handler=eh, op="get_domain_name")109def get_domain_name(prev_state, domain_name, desired_config, desired_tls_config, tags, region):110 if prev_state and prev_state.get("props", {}).get("name"):111 old_domain_name = prev_state["props"]["name"]112 if old_domain_name and (old_domain_name != domain_name):113 eh.add_op("remove_old", {"name": old_domain_name, "create_and_remove": True})114 try:115 response = v2.get_domain_name(DomainName=domain_name)116 print(f'Selection Expression = {response.get("ApiMappingSelectionExpression")}')117 print(f"response = {response}")118 eh.add_log("Got Domain Name", response)119 config = response.get("DomainNameConfigurations")[0]120 tls_config = response.get("MutualTlsAuthentication")121 desired_config['CertificateArn'] = eh.props['certificate_arn']122 match = True123 for k, v in desired_config.items():124 if v != config[k]:125 eh.add_op("update_domain_name")126 match = False127 if match:128 for k,v in desired_tls_config.items():129 if v != tls_config[k]:130 eh.add_op("update_domain_name")131 match = False132 if match:133 eh.add_props({134 "hosted_zone_id": config.get("HostedZoneId"),135 "api_gateway_domain_name": config.get("ApiGatewayDomainName")136 })137 eh.add_links({"AWS Custom Domain Name": gen_custom_domain_link(domain_name, region),138 "URL": gen_domain_url(domain_name)})139 eh.add_log("Domain Update Unncessary", {"config": config, "desired_config": desired_config})140 current_tags = response.get("Tags") or {}141 if tags != current_tags:142 remove_tags = [k for k in current_tags.keys() if k not in tags]143 add_tags = {k:v for k,v in tags.items() if k not in current_tags.keys()}144 if remove_tags:145 eh.add_op("remove_tags", remove_tags)146 if add_tags:147 eh.add_op("add_tags", add_tags)148 except ClientError as e:149 if e.response['Error']['Code'] == "NotFoundException":150 eh.add_op("create_domain_name")151 eh.add_log("Domain Name Does Not Exist", {"domain_name": domain_name})152 else:153 handle_common_errors(e, eh, "Get Domain Name Failed", 10)154 155@ext(handler=eh, op="create_domain_name")156def create_domain_name(domain_name, desired_config, desired_tls_config, tags, region):157 try:158 params = remove_none_attributes({159 "DomainName": domain_name,160 "DomainNameConfigurations": [desired_config],161 "MutualTlsAuthentication": desired_tls_config or None,162 "Tags": tags or None163 })164 response = v2.create_domain_name(**params)165 print(f"create response {response}")166 eh.add_log("Created Domain Name", response)167 config = response['DomainNameConfigurations'][0]168 eh.add_props({169 "hosted_zone_id": config.get("HostedZoneId"),170 "api_gateway_domain_name": config.get("ApiGatewayDomainName")171 })172 eh.add_links({173 "AWS Custom Domain Name": gen_custom_domain_link(domain_name, region),174 "URL": gen_domain_url(domain_name)175 })176 except ClientError as e:177 handle_common_errors(e, eh, "Create Failure", 35, 178 ["NotFoundException", "BadRequestException", "AccessDeniedException"]179 )180@ext(handler=eh, op="update_domain_name")181def update_domain_name(domain_name, desired_config, desired_tls_config, region):182 try:183 params = remove_none_attributes({184 "DomainName": domain_name,185 "DomainNameConfigurations": [desired_config],186 "MutualTlsAuthentication": desired_tls_config or None,187 })188 response = v2.update_domain_name(**params)189 print(f"update response {response}")190 eh.add_log("Updated Domain Name", response)191 config = response['DomainNameConfigurations'][0]192 eh.add_props({193 "hosted_zone_id": config.get("HostedZoneId"),194 "api_gateway_domain_name": config.get("ApiGatewayDomainName")195 })196 eh.add_links({197 "AWS Custom Domain Name": gen_custom_domain_link(domain_name, region),198 "URL": gen_domain_url(domain_name)199 })200 except ClientError as e:201 handle_common_errors(e, eh, "Update Failure", 35, 202 ["NotFoundException", "BadRequestException", "AccessDeniedException"]...
management.py
Source:management.py
...42 43 if answer.lower() in ('y', 'yes'):44 cursor = connection.cursor()45 cursor.execute("ALTER TABLE auth_user MODIFY COLUMN username varchar(75) NOT NULL")46def update_domain_name(sender, app, created_models, verbosity, interactive, **kwargs):47 """48 Updates default domain name. If non-interactive, uses a sane default that49 is compatible with local Facebook development.50 """51 from django.contrib.sites.models import Site52 if Site in created_models and interactive:53 msg = "\nYou just installed Django's sites system. What domain name " \54 "would you like to use?\nEnter a domain such as \"cardstories.org\": "55 domain = raw_input(msg)56 s = Site.objects.get(id=1)57 s.domain = domain58 s.name = domain59 s.save()60post_syncdb.connect(update_username_column)...
tests.py
Source:tests.py
1"""2As this is a django internal template, we disable pylint3"""4# pylint: disable=W06115from django.test import TestCase6from django.core.exceptions import ObjectDoesNotExist7from slam_domain.models import Domain, DomainEntry8DOMAIN_OPTIONS_EMPTY = {9 'dns_master': '127.0.0.1'10}11DOMAIN_OPTIONS_FULL = {12 'dns_master': '127.0.0.1',13 'description': 'This is a test',14 'contact': 'ns-master@full.com',15 'creation_date': '2020-01-01'16}17EMPTY_DOMAIN_NAME = 'empty.com'18FULL_DOMAIN_NAME = 'full.com'19DELETE_DOMAIN_NAME = 'delete.com'20UPDATE_DOMAIN_NAME = 'update.com'21class DomainTestCase(TestCase):22 def setUp(self) -> None:23 Domain.create(name=EMPTY_DOMAIN_NAME, args=DOMAIN_OPTIONS_EMPTY)24 Domain.create(name=FULL_DOMAIN_NAME, args=DOMAIN_OPTIONS_FULL)25 Domain.create(name=DELETE_DOMAIN_NAME, args=DOMAIN_OPTIONS_EMPTY)26 Domain.create(name=UPDATE_DOMAIN_NAME, args=DOMAIN_OPTIONS_EMPTY)27 def test_domain_get(self):28 empty_com = Domain.objects.get(name=EMPTY_DOMAIN_NAME)29 full_com = Domain.objects.get(name=FULL_DOMAIN_NAME)30 self.assertEqual(empty_com.dns_master, DOMAIN_OPTIONS_EMPTY['dns_master'])31 self.assertIsNone(empty_com.description)32 self.assertIsNone(empty_com.contact)33 self.assertIsNotNone(empty_com.creation_date)34 self.assertEqual(full_com.dns_master, DOMAIN_OPTIONS_FULL['dns_master'])35 self.assertEqual(full_com.description, DOMAIN_OPTIONS_FULL['description'])36 self.assertEqual(full_com.contact, DOMAIN_OPTIONS_FULL['contact'])37 self.assertIsNotNone(full_com.creation_date)38 def test_domain_delete(self):39 Domain.remove(name=DELETE_DOMAIN_NAME)40 with self.assertRaisesMessage(ObjectDoesNotExist, 'Domain matching query does not exist.'):41 Domain.objects.get(name=DELETE_DOMAIN_NAME)42 def test_domain_update(self):43 Domain.update(name=UPDATE_DOMAIN_NAME, args=DOMAIN_OPTIONS_FULL)44 update_com = Domain.objects.get(name=UPDATE_DOMAIN_NAME)45 self.assertEqual(update_com.dns_master, DOMAIN_OPTIONS_FULL['dns_master'])46 self.assertEqual(update_com.description, DOMAIN_OPTIONS_FULL['description'])...
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!!