Best Python code snippet using localstack_python
transformer_utility.py
Source:transformer_utility.py  
...39        :return: KeyValueBasedTransformer40        """41        return KeyValueBasedTransformer(42            lambda k, v: v if k == key else None,43            replacement=value_replacement or _replace_camel_string_with_hyphen(key),44            replace_reference=reference_replacement,45        )46    @staticmethod47    def jsonpath(jsonpath: str, value_replacement: str, reference_replacement: bool = True):48        """Creates a new JsonpathTransformer. If the jsonpath matches, the value will be replaced.49        :param jsonpath: the jsonpath that should be matched50        :param value_replacement: the value which will replace the original value.51        By default it is the key-name in lowercase, separated with hyphen52        :param reference_replacement: if False, only the original value for this key will be replaced.53        If True all references of this value will be replaced (using a regex pattern), for the entire test case.54        In this case, the replaced value will be nummerated as well.55        Default: True56        :return: JsonpathTransformer57        """58        return JsonpathTransformer(59            jsonpath=jsonpath,60            replacement=value_replacement,61            replace_reference=reference_replacement,62        )63    @staticmethod64    def regex(regex: str | Pattern[str], replacement: str):65        """Creates a new RegexTransformer. All matches in the string-converted dict will be replaced.66        :param regex: the regex that should be matched67        :param replacement: the value which will replace the original value.68        :return: RegexTransformer69        """70        return RegexTransformer(regex, replacement)71    # TODO add more utility functions? e.g. key_value with function as parameter?72    @staticmethod73    def lambda_api():74        """75        :return: array with Transformers, for lambda api.76        """77        return [78            TransformerUtility.key_value("FunctionName"),79            TransformerUtility.jsonpath(80                jsonpath="$..Code.Location",81                value_replacement="<location>",82                reference_replacement=False,83            ),84            KeyValueBasedTransformer(_resource_name_transformer, "resource"),85            KeyValueBasedTransformer(86                _log_stream_name_transformer, "log-stream-name", replace_reference=True87            ),88        ]89    @staticmethod90    def cloudformation_api():91        """92        :return: array with Transformers, for cloudformation api.93        """94        return [95            TransformerUtility.key_value("ChangeSetName"),96            TransformerUtility.key_value("StackName"),97            KeyValueBasedTransformer(_resource_name_transformer, "resource"),98            KeyValueBasedTransformer(_change_set_id_transformer, "change-set-id"),99        ]100    @staticmethod101    def iam_api():102        """103        :return: array with Transformers, for iam api.104        """105        return [TransformerUtility.key_value("UserName"), TransformerUtility.key_value("UserId")]106    @staticmethod107    def s3_api():108        """109        :return: array with Transformers, for s3 api.110        """111        return [112            TransformerUtility.key_value("Name", value_replacement="bucket-name"),113            TransformerUtility.jsonpath(114                jsonpath="$..Owner.DisplayName",115                value_replacement="<display-name>",116                reference_replacement=False,117            ),118            TransformerUtility.jsonpath(119                jsonpath="$..Owner.ID", value_replacement="<owner-id>", reference_replacement=False120            ),121            # for s3 notifications:122            TransformerUtility.jsonpath(123                "$..responseElements.x-amz-id-2", "amz-id", reference_replacement=False124            ),125            TransformerUtility.jsonpath(126                "$..responseElements.x-amz-request-id",127                "amz-request-id",128                reference_replacement=False,129            ),130            TransformerUtility.jsonpath("$..s3.configurationId", "config-id"),131            TransformerUtility.jsonpath(132                "$..s3.object.sequencer", "sequencer", reference_replacement=False133            ),134            TransformerUtility.jsonpath("$..s3.bucket.ownerIdentity.principalId", "principal-id"),135            TransformerUtility.jsonpath("$..userIdentity.principalId", "principal-id"),136            TransformerUtility.jsonpath("$..requestParameters.sourceIPAddress", "ip-address"),137            TransformerUtility.jsonpath(138                "$..s3.object.versionId",139                "version-id",140                reference_replacement=False,141            ),142        ]143    @staticmethod144    def sqs_api():145        """146        :return: array with Transformers, for sqs api.147        """148        return [149            TransformerUtility.key_value("ReceiptHandle"),150            TransformerUtility.key_value("SenderId"),151            TransformerUtility.jsonpath("$..MessageAttributes.RequestID.StringValue", "request-id"),152            KeyValueBasedTransformer(_resource_name_transformer, "resource"),153            KeyValueBasedTransformer(_signing_cert_url_token_transformer, replacement="token"),154            KeyValueBasedTransformer(155                _sns_pem_file_token_transformer, replacement="signing-cert-file"156            ),157            # replaces the domain in "UnsubscribeURL"158            TransformerUtility.regex(159                re.compile(160                    r"(?<=UnsubscribeURL[\"|']:\s[\"|'])(https?.*?)(?=/\?Action=Unsubscribe)"161                ),162                replacement="<unsubscribe-domain>",163            ),164        ]165    @staticmethod166    def cloudwatch_api():167        """168        :return: array with Transformers, for cloudwatch api.169        """170        return [171            TransformerUtility.key_value("AlarmName"),172            KeyValueBasedTransformer(_resource_name_transformer, "SubscriptionArn"),173            TransformerUtility.key_value("Region", "region-name-full"),174        ]175    @staticmethod176    def secretsmanager_secret_id_arn(create_secret_res: CreateSecretResponse, index: int):177        secret_id_repl = f"<SecretId-{index}idx>"178        arn_part_repl = f"<ArnPart-{index}idx>"179        secret_id: str = create_secret_res["Name"]180        arn_part: str = "".join(create_secret_res["ARN"].rpartition("-")[-2:])181        return [182            RegexTransformer(arn_part, arn_part_repl),183            RegexTransformer(secret_id, secret_id_repl),184        ]185    # TODO add example186    # @staticmethod187    # def custom(fn: Callable[[dict], dict]) -> Transformer:188    #     return GenericTransformer(fn)189def _sns_pem_file_token_transformer(key: str, val: str) -> str:190    if isinstance(val, str) and key == "SigningCertURL":191        pattern = re.compile(r".*SimpleNotificationService-(.*)?\.pem")192        match = re.match(pattern, val)193        if match:194            return match.groups()[0]195def _signing_cert_url_token_transformer(key: str, val: str) -> str:196    if isinstance(val, str) and key == "UnsubscribeURL":197        pattern = re.compile(r".*(?<=\?Action=Unsubscribe&SubscriptionArn=).*:(.*)")198        match = re.match(pattern, val)199        if match:200            return match.groups()[0]201def _replace_camel_string_with_hyphen(input_string: str):202    return "".join(["-" + char.lower() if char.isupper() else char for char in input_string]).strip(203        "-"204    )205def _log_stream_name_transformer(key: str, val: str) -> str:206    if isinstance(val, str) and (key == "log_stream_name" or key == "logStreamName"):207        match = re.match(PATTERN_LOGSTREAM_ID, val)208        if match:209            return val210    return None211def _resource_name_transformer(key: str, val: str) -> str:212    if isinstance(val, str):213        match = re.match(PATTERN_ARN, val)214        if match:215            res = match.groups()[-1]...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!!
