Skip to content

Commit

Permalink
Introduce a TextTransformer to replace strings with special chars
Browse files Browse the repository at this point in the history
  • Loading branch information
bblommers committed Dec 20, 2024
1 parent dc65d10 commit 2c93b18
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
16 changes: 16 additions & 0 deletions localstack_snapshot/snapshots/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 12 additions & 0 deletions localstack_snapshot/snapshots/transformer_utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
JsonpathTransformer,
KeyValueBasedTransformer,
RegexTransformer,
TextTransformer,
)


Expand Down Expand Up @@ -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)
26 changes: 26 additions & 0 deletions tests/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <value> with more text"}

# Matching this against a regex does not work, because the + is a special character
transformer = TransformerUtility.text(value, "<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):
Expand Down

0 comments on commit 2c93b18

Please sign in to comment.