localstack-snapshot 0.3.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/PKG-INFO +1 -1
  2. localstack_snapshot-0.3.1/localstack_snapshot/__init__.py +1 -0
  3. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/snapshots/prototype.py +38 -2
  4. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/snapshots/report.py +8 -1
  5. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/snapshots/transformer.py +6 -0
  6. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot.egg-info/PKG-INFO +1 -1
  7. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/pyproject.toml +1 -1
  8. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/tests/test_snapshots.py +139 -0
  9. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/tests/test_transformer.py +79 -0
  10. localstack_snapshot-0.3.0/localstack_snapshot/__init__.py +0 -1
  11. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/LICENSE +0 -0
  12. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/README.md +0 -0
  13. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/pytest/__init__.py +0 -0
  14. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/pytest/snapshot.py +0 -0
  15. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/snapshots/__init__.py +0 -0
  16. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/snapshots/transformer_utility.py +0 -0
  17. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/util/__init__.py +0 -0
  18. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot/util/encoding.py +0 -0
  19. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot.egg-info/SOURCES.txt +0 -0
  20. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot.egg-info/dependency_links.txt +0 -0
  21. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot.egg-info/requires.txt +0 -0
  22. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/localstack_snapshot.egg-info/top_level.txt +0 -0
  23. {localstack_snapshot-0.3.0 → localstack_snapshot-0.3.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: localstack-snapshot
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Extracted snapshot testing lib for LocalStack
5
5
  Author-email: LocalStack Contributors <info@localstack.cloud>
6
6
  License:
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -25,6 +25,8 @@ from .transformer_utility import TransformerUtility
25
25
  SNAPSHOT_LOGGER = logging.getLogger(__name__)
26
26
  SNAPSHOT_LOGGER.setLevel(logging.DEBUG if os.environ.get("DEBUG_SNAPSHOT") else logging.WARNING)
27
27
 
28
+ _SKIP_PLACEHOLDER_VALUE = "$__to_be_skipped__$"
29
+
28
30
 
29
31
  class SnapshotMatchResult:
30
32
  def __init__(self, a: dict, b: dict, key: str = ""):
@@ -218,7 +220,7 @@ class SnapshotSession:
218
220
  self.skip_verification_paths = skip_verification_paths or []
219
221
  if skip_verification_paths:
220
222
  SNAPSHOT_LOGGER.warning(
221
- f"Snapshot verification disabled for paths: {skip_verification_paths}"
223
+ "Snapshot verification disabled for paths: %s", skip_verification_paths
222
224
  )
223
225
 
224
226
  if self.update:
@@ -306,7 +308,7 @@ class SnapshotSession:
306
308
  try:
307
309
  replaced_tmp[key] = json.loads(dumped_value)
308
310
  except JSONDecodeError:
309
- SNAPSHOT_LOGGER.error(f"could not decode json-string:\n{tmp}")
311
+ SNAPSHOT_LOGGER.error("could not decode json-string:\n%s", tmp)
310
312
  return {}
311
313
 
312
314
  return replaced_tmp
@@ -365,6 +367,23 @@ class SnapshotSession:
365
367
 
366
368
  return full_path_nodes[::-1][1:] # reverse the list and remove Root()/$
367
369
 
370
+ def _remove_placeholder(_tmp):
371
+ """Traverse the object and remove any values in a list that would be equal to the placeholder"""
372
+ if isinstance(_tmp, dict):
373
+ for k, v in _tmp.items():
374
+ if isinstance(v, dict):
375
+ _remove_placeholder(v)
376
+ elif isinstance(v, list):
377
+ _tmp[k] = _remove_placeholder(v)
378
+ elif isinstance(_tmp, list):
379
+ return [
380
+ _remove_placeholder(item) for item in _tmp if item != _SKIP_PLACEHOLDER_VALUE
381
+ ]
382
+
383
+ return _tmp
384
+
385
+ has_placeholder = False
386
+
368
387
  for path in self.skip_verification_paths:
369
388
  matches = parse(path).find(tmp) or []
370
389
  for m in matches:
@@ -378,7 +397,24 @@ class SnapshotSession:
378
397
  helper = helper.get(p, None)
379
398
  if not helper:
380
399
  continue
400
+
381
401
  if (
382
402
  isinstance(helper, dict) and full_path[-1] in helper.keys()
383
403
  ): # might have been deleted already
384
404
  del helper[full_path[-1]]
405
+ elif isinstance(helper, list):
406
+ try:
407
+ index = int(full_path[-1].lstrip("[").rstrip("]"))
408
+ # we need to set a placeholder value as the skips are based on index
409
+ # if we are to pop the values, the next skip index will have shifted and won't be correct
410
+ helper[index] = _SKIP_PLACEHOLDER_VALUE
411
+ has_placeholder = True
412
+ except ValueError:
413
+ SNAPSHOT_LOGGER.warning(
414
+ "Snapshot skip path '%s' was not applied as it was invalid for that snapshot",
415
+ path,
416
+ exc_info=SNAPSHOT_LOGGER.isEnabledFor(logging.DEBUG),
417
+ )
418
+
419
+ if has_placeholder:
420
+ _remove_placeholder(tmp)
@@ -1,4 +1,5 @@
1
1
  import logging
2
+ import re
2
3
 
3
4
  from localstack_snapshot.snapshots import SnapshotMatchResult
4
5
 
@@ -29,6 +30,8 @@ _esctable = {
29
30
  "underlined": 4,
30
31
  }
31
32
 
33
+ _regular_json_path_chars_regex = re.compile("[a-zA-Z0-9_-]+")
34
+
32
35
 
33
36
  class PatchPath(str):
34
37
  """
@@ -52,7 +55,11 @@ def _format_json_path(path: list):
52
55
  json_str = "$.."
53
56
  for idx, elem in enumerate(path):
54
57
  if not isinstance(elem, int):
55
- json_str += str(elem)
58
+ _elem = str(elem)
59
+ # we want to wrap in single quotes parts with special characters so that users can copy-paste them directly
60
+ if not _regular_json_path_chars_regex.fullmatch(_elem):
61
+ _elem = f"'{_elem}'"
62
+ json_str += _elem
56
63
  if idx < len(path) - 1 and not json_str.endswith(".."):
57
64
  json_str += "."
58
65
 
@@ -102,8 +102,14 @@ class ResponseMetaDataTransformer:
102
102
  if k == "ResponseMetadata":
103
103
  metadata = v
104
104
  http_headers = metadata.get("HTTPHeaders")
105
+ if not isinstance(http_headers, dict):
106
+ continue
107
+
105
108
  # TODO "x-amz-bucket-region"
106
109
  # TestS3.test_region_header_exists -> verifies bucket-region
110
+
111
+ # FIXME: proper value is `content-type` with no underscore in lowercase, but this will necessitate a
112
+ # refresh of all snapshots
107
113
  headers_to_collect = ["content_type"]
108
114
  simplified_headers = {}
109
115
  for h in headers_to_collect:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: localstack-snapshot
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Extracted snapshot testing lib for LocalStack
5
5
  Author-email: LocalStack Contributors <info@localstack.cloud>
6
6
  License:
@@ -7,7 +7,7 @@ name = "localstack-snapshot"
7
7
  authors = [
8
8
  { name = "LocalStack Contributors", email = "info@localstack.cloud" }
9
9
  ]
10
- version = "0.3.0"
10
+ version = "0.3.1"
11
11
  description = "Extracted snapshot testing lib for LocalStack"
12
12
  dependencies = [
13
13
  "jsonpath-ng>1.6",
@@ -191,6 +191,137 @@ class TestSnapshotManager:
191
191
  sm.match("key1", [{"key2": "value1"}, "value2", 3])
192
192
  sm._assert_all()
193
193
 
194
+ def test_list_as_last_node_in_skip_verification_path(self):
195
+ sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
196
+ sm.recorded_state = {"key_a": {"aaa": ["item1", "item2", "item3"]}}
197
+ sm.match(
198
+ "key_a",
199
+ {"aaa": ["item1", "different-value"]},
200
+ )
201
+
202
+ with pytest.raises(Exception) as ctx: # asserts it fail without skipping
203
+ sm._assert_all()
204
+ ctx.match("Parity snapshot failed")
205
+
206
+ skip_path = ["$..aaa[1]", "$..aaa[2]"]
207
+ sm._assert_all(skip_verification_paths=skip_path)
208
+
209
+ skip_path = ["$..aaa.1", "$..aaa.2"]
210
+ sm._assert_all(skip_verification_paths=skip_path)
211
+
212
+ def test_list_as_last_node_in_skip_verification_path_complex(self):
213
+ sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
214
+ sm.recorded_state = {
215
+ "key_a": {
216
+ "aaa": [
217
+ {"aab": ["aac", "aad"]},
218
+ {"aab": ["aac", "aad"]},
219
+ {"aab": ["aac", "aad"]},
220
+ ]
221
+ }
222
+ }
223
+ sm.match(
224
+ "key_a",
225
+ {
226
+ "aaa": [
227
+ {"aab": ["aac", "bad-value"], "bbb": "value"},
228
+ {"aab": ["aac", "aad", "bad-value"]},
229
+ {"aab": ["bad-value", "aad"]},
230
+ ]
231
+ },
232
+ )
233
+
234
+ with pytest.raises(Exception) as ctx: # asserts it fail without skipping
235
+ sm._assert_all()
236
+ ctx.match("Parity snapshot failed")
237
+
238
+ skip_path = [
239
+ "$..aaa[0].aab[1]",
240
+ "$..aaa[0].bbb",
241
+ "$..aaa[1].aab[2]",
242
+ "$..aaa[2].aab[0]",
243
+ ]
244
+ sm._assert_all(skip_verification_paths=skip_path)
245
+
246
+ skip_path = [
247
+ "$..aaa.0..aab.1",
248
+ "$..aaa.0..bbb",
249
+ "$..aaa.1..aab.2",
250
+ "$..aaa.2..aab.0",
251
+ ]
252
+ sm._assert_all(skip_verification_paths=skip_path)
253
+
254
+ def test_list_as_mid_node_in_skip_verification_path(self):
255
+ sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
256
+ sm.recorded_state = {"key_a": {"aaa": [{"aab": "value1"}, {"aab": "value2"}]}}
257
+ sm.match(
258
+ "key_a",
259
+ {"aaa": [{"aab": "value1"}, {"aab": "bad-value"}]},
260
+ )
261
+
262
+ with pytest.raises(Exception) as ctx: # asserts it fail without skipping
263
+ sm._assert_all()
264
+ ctx.match("Parity snapshot failed")
265
+
266
+ skip_path = ["$..aaa[1].aab"]
267
+ sm._assert_all(skip_verification_paths=skip_path)
268
+
269
+ skip_path = ["$..aaa.1.aab"]
270
+ sm._assert_all(skip_verification_paths=skip_path)
271
+
272
+ def test_list_as_last_node_in_skip_verification_path_nested(self):
273
+ sm = SnapshotSession(scope_key="A", verify=True, base_file_path="", update=False)
274
+ sm.recorded_state = {
275
+ "key_a": {
276
+ "aaa": [
277
+ "bbb",
278
+ "ccc",
279
+ [
280
+ "ddd",
281
+ "eee",
282
+ [
283
+ "fff",
284
+ "ggg",
285
+ ],
286
+ ],
287
+ ]
288
+ }
289
+ }
290
+ sm.match(
291
+ "key_a",
292
+ {
293
+ "aaa": [
294
+ "bbb",
295
+ "ccc",
296
+ [
297
+ "bad-value",
298
+ "eee",
299
+ [
300
+ "fff",
301
+ "ggg",
302
+ ],
303
+ ],
304
+ ]
305
+ },
306
+ )
307
+
308
+ with pytest.raises(Exception) as ctx: # asserts it fail without skipping
309
+ sm._assert_all()
310
+ ctx.match("Parity snapshot failed")
311
+
312
+ skip_path = ["$..aaa[2][0]"]
313
+ sm._assert_all(skip_verification_paths=skip_path)
314
+
315
+ skip_path = ["$..aaa.2[0]"]
316
+ sm._assert_all(skip_verification_paths=skip_path)
317
+
318
+ # these 2 will actually skip almost everything, as they will match every first element of any list inside `aaa`
319
+ skip_path = ["$..aaa..[0]"]
320
+ sm._assert_all(skip_verification_paths=skip_path)
321
+
322
+ skip_path = ["$..aaa..0"]
323
+ sm._assert_all(skip_verification_paths=skip_path)
324
+
194
325
 
195
326
  def test_json_diff_format():
196
327
  path = ["Records", 1]
@@ -209,6 +340,14 @@ def test_json_diff_format():
209
340
  assert _format_json_path(path) == '"$.."'
210
341
  path = [1, 1, 0, "SomeKey"]
211
342
  assert _format_json_path(path) == '"$..SomeKey"'
343
+ path = ["Some:Key"]
344
+ assert _format_json_path(path) == "\"$..'Some:Key'\""
345
+ path = ["Some.Key"]
346
+ assert _format_json_path(path) == "\"$..'Some.Key'\""
347
+ path = ["Some-Key"]
348
+ assert _format_json_path(path) == '"$..Some-Key"'
349
+ path = ["Some0Key"]
350
+ assert _format_json_path(path) == '"$..Some0Key"'
212
351
 
213
352
 
214
353
  def test_sorting_transformer():
@@ -5,6 +5,7 @@ import pytest
5
5
 
6
6
  from localstack_snapshot.snapshots.transformer import (
7
7
  JsonStringTransformer,
8
+ ResponseMetaDataTransformer,
8
9
  SortingTransformer,
9
10
  TimestampTransformer,
10
11
  TransformContext,
@@ -405,3 +406,81 @@ class TestTimestampTransformer:
405
406
  ctx = TransformContext()
406
407
  output = transformer.transform(input, ctx=ctx)
407
408
  assert output == expected
409
+
410
+
411
+ class TestResponseMetaDataTransformer:
412
+ def test_with_headers(self):
413
+ input_data = {"ResponseMetadata": {"HTTPHeaders": {"header1": "value1"}}}
414
+
415
+ metadata_transformer = ResponseMetaDataTransformer()
416
+
417
+ expected_key_value = {"ResponseMetadata": {"HTTPHeaders": {}}}
418
+
419
+ copied = copy.deepcopy(input_data)
420
+ ctx = TransformContext()
421
+ assert metadata_transformer.transform(copied, ctx=ctx) == expected_key_value
422
+ assert ctx.serialized_replacements == []
423
+
424
+ def test_with_headers_and_status_code(self):
425
+ input_data = {
426
+ "ResponseMetadata": {"HTTPHeaders": {"header1": "value1"}, "HTTPStatusCode": 500}
427
+ }
428
+
429
+ metadata_transformer = ResponseMetaDataTransformer()
430
+
431
+ expected_key_value = {"ResponseMetadata": {"HTTPHeaders": {}, "HTTPStatusCode": 500}}
432
+
433
+ copied = copy.deepcopy(input_data)
434
+ ctx = TransformContext()
435
+ assert metadata_transformer.transform(copied, ctx=ctx) == expected_key_value
436
+ assert ctx.serialized_replacements == []
437
+
438
+ def test_with_status_code_only(self):
439
+ input_data = {"ResponseMetadata": {"HTTPStatusCode": 500, "RandomData": "random"}}
440
+
441
+ metadata_transformer = ResponseMetaDataTransformer()
442
+
443
+ expected_key_value = {"ResponseMetadata": {"HTTPStatusCode": 500, "RandomData": "random"}}
444
+
445
+ copied = copy.deepcopy(input_data)
446
+ ctx = TransformContext()
447
+ assert metadata_transformer.transform(copied, ctx=ctx) == expected_key_value
448
+ assert ctx.serialized_replacements == []
449
+
450
+ def test_with_empty_response_metadata(self):
451
+ input_data = {"ResponseMetadata": {"NotHeaders": "data"}}
452
+
453
+ metadata_transformer = ResponseMetaDataTransformer()
454
+
455
+ expected_key_value = {"ResponseMetadata": {"NotHeaders": "data"}}
456
+
457
+ copied = copy.deepcopy(input_data)
458
+ ctx = TransformContext()
459
+ assert metadata_transformer.transform(copied, ctx=ctx) == expected_key_value
460
+ assert ctx.serialized_replacements == []
461
+
462
+ def test_with_headers_wrong_type(self):
463
+ input_data = {"ResponseMetadata": {"HTTPHeaders": "data"}}
464
+
465
+ metadata_transformer = ResponseMetaDataTransformer()
466
+
467
+ expected_key_value = {"ResponseMetadata": {"HTTPHeaders": "data"}}
468
+
469
+ copied = copy.deepcopy(input_data)
470
+ ctx = TransformContext()
471
+ assert metadata_transformer.transform(copied, ctx=ctx) == expected_key_value
472
+ assert ctx.serialized_replacements == []
473
+
474
+ def test_headers_filtering(self):
475
+ input_data = {
476
+ "ResponseMetadata": {"HTTPHeaders": {"content_type": "value1", "header1": "value1"}}
477
+ }
478
+
479
+ metadata_transformer = ResponseMetaDataTransformer()
480
+
481
+ expected_key_value = {"ResponseMetadata": {"HTTPHeaders": {"content_type": "value1"}}}
482
+
483
+ copied = copy.deepcopy(input_data)
484
+ ctx = TransformContext()
485
+ assert metadata_transformer.transform(copied, ctx=ctx) == expected_key_value
486
+ assert ctx.serialized_replacements == []
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"