-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmocks.py
59 lines (45 loc) · 1.81 KB
/
mocks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import json
import warnings
from supermutes.dot import dotify
class AbeMock(object):
def __init__(self, data):
"""
Initialise an ABE mock from data.
"""
if not isinstance(data, dict):
msg = ('Instanciating an AbeMock by filename is deprecated and '
'will be removed in an upcoming release. '
'Use AbeMock.from_filename instead'.format(data))
warnings.warn(msg, DeprecationWarning)
with open(data, 'r') as f:
data = json.load(f)
# map JSON fields to attributes
self.__dict__ = data
# Make all example requests and reponses accessible via dot syntax
# (e.g. mock["OK"].request.status)
for key, value in self.examples.items():
# Add the request URL automatically if missing.
self._feed_inherited_fields(value, 'request', ['url', 'method'])
self.examples[key] = dotify(value)
@classmethod
def from_filename(cls, filename):
"""
Initialise an ABE mock from a spec file.
filename is expected to be the path to an ABE file.
"""
with open(filename, 'r') as f:
data = json.load(f)
return AbeMock(data)
def _feed_inherited_fields(self, value, where, inheritable):
"""
If missing in request or response, some fields are inherited.
URL and method are defined at the top level. They don't need to be
redefined in example requests or responses.
:param where: 'request' or 'response'
:param inheritable: list of inheritable fields
"""
if where not in value:
value[where] = {}
for key in inheritable:
if key not in value[where]:
value[where][key] = getattr(self, key)