From 2ec064a933eb5c4bab7e5d3dca7ec05f5876bdb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Abdelkader=20Mart=C3=ADnez=20P=C3=A9rez?= Date: Wed, 21 Aug 2019 13:01:56 +0200 Subject: [PATCH] Allow special marker ANY inside JSON examples --- spec/test/features/steps/comparedict.py | 6 ++++++ spec/test/features/steps/jsonexample.py | 24 ++++++++++++++++++++++++ spec/test/features/steps/steps.py | 3 ++- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 spec/test/features/steps/jsonexample.py diff --git a/spec/test/features/steps/comparedict.py b/spec/test/features/steps/comparedict.py index c720ee6..2ba6a81 100644 --- a/spec/test/features/steps/comparedict.py +++ b/spec/test/features/steps/comparedict.py @@ -1,4 +1,5 @@ from functools import singledispatch +from jsonexample import ANY def assert_same_type(f): @@ -40,3 +41,8 @@ def _(model, obj): @assert_same_type def _(model, obj): return model <= obj + + +@is_subset.register(ANY) +def _(model, obj): + return True diff --git a/spec/test/features/steps/jsonexample.py b/spec/test/features/steps/jsonexample.py new file mode 100644 index 0000000..19e9290 --- /dev/null +++ b/spec/test/features/steps/jsonexample.py @@ -0,0 +1,24 @@ +import json +from functools import partial +import re + + +class ANY: + pass + + +class ExampleDecoder(json.JSONDecoder): + def __init__(self, *args, **kwargs): + super().__init__(*args, object_hook=self.object_hook, **kwargs) + + def decode(self, s, *args, **kwargs): + s = re.sub(r'(\W)(ANY)(\W)', r'\1{"_type": "ANY"}\3', s) + return super().decode(s, *args, **kwargs) + + def object_hook(self, dct): + if dct.get('_type', None) == 'ANY': + return ANY() + else: + return dct + +loads = partial(json.loads, cls=ExampleDecoder) diff --git a/spec/test/features/steps/steps.py b/spec/test/features/steps/steps.py index e82d71a..c6e87c6 100644 --- a/spec/test/features/steps/steps.py +++ b/spec/test/features/steps/steps.py @@ -8,6 +8,7 @@ import subprocess import requests from environconfig import EnvironConfig, StringVar, IntVar, BooleanVar from comparedict import is_subset +import jsonexample import logging @@ -134,7 +135,7 @@ def step_impl(context, reason): @then('I get the following response body') def step_impl(context): - assert is_subset(json.loads(context.text), context.response.json()) + assert is_subset(jsonexample.loads(context.text), context.response.json()) @then('I get an empty response body')