diff --git a/localstack_snapshot/snapshots/transformer.py b/localstack_snapshot/snapshots/transformer.py index a823669..4c484e6 100644 --- a/localstack_snapshot/snapshots/transformer.py +++ b/localstack_snapshot/snapshots/transformer.py @@ -344,3 +344,19 @@ def _transform_dict(self, input_data: dict, ctx: TransformContext = None) -> dic def _transform_list(self, input_data: list, ctx: TransformContext = None) -> list: return [self._transform(e, ctx=ctx) for e in input_data] + + +class TextTransformer: + def __init__(self, text: str, replacement: str): + self.text = text + self.replacement = replacement + + def transform(self, input_data: dict, *, ctx: TransformContext) -> dict: + def replace_val(s): + return s.replace(self.text, self.replacement) + + ctx.register_serialized_replacement(replace_val) + SNAPSHOT_LOGGER.debug( + f"Registering text pattern '{self.text}' in snapshot with '{self.replacement}'" + ) + return input_data diff --git a/localstack_snapshot/snapshots/transformer_utility.py b/localstack_snapshot/snapshots/transformer_utility.py index 6f08127..bc35a0a 100644 --- a/localstack_snapshot/snapshots/transformer_utility.py +++ b/localstack_snapshot/snapshots/transformer_utility.py @@ -5,6 +5,7 @@ JsonpathTransformer, KeyValueBasedTransformer, RegexTransformer, + TextTransformer, ) @@ -67,3 +68,14 @@ def regex(regex: str | Pattern[str], replacement: str): :return: RegexTransformer """ return RegexTransformer(regex, replacement) + + @staticmethod + def text(text: str, replacement: str): + """Creates a new TextTransformer. All occurrences in the string-converted dict will be replaced. + + :param text: the text that should be replaced + :param replacement: the value which will replace the original value. + + :return: RegexTransformer + """ + return TextTransformer(text, replacement) diff --git a/tests/test_transformer.py b/tests/test_transformer.py index 711efc1..5e05824 100644 --- a/tests/test_transformer.py +++ b/tests/test_transformer.py @@ -211,6 +211,32 @@ def test_nested_sorting_transformer(self): output = transformer.transform(input, ctx=ctx) assert output == expected + @pytest.mark.parametrize( + "value", + [ + "a+b", + "question?", + "amount: $4.00", + "emoji: ^^", + "sentence.", + "others (like so)", + "special {char}", + ], + ) + def test_text(self, value): + input = {"key": f"some {value} with more text"} + + expected = {"key": "some with more text"} + + # Matching this against a regex does not work, because the + is a special character + transformer = TransformerUtility.text(value, "") + + ctx = TransformContext() + output = transformer.transform(json.dumps(input), ctx=ctx) + for sr in ctx.serialized_replacements: + output = sr(output) + assert json.loads(output) == expected + class TestTimestampTransformer: def test_generic_timestamp_transformer(self):