-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmock.py
242 lines (188 loc) · 6.05 KB
/
smock.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import json
import yaml
"""
SMock -- Serverboards Mock library -- Mock comfortably.
This library helps to mock function and method calls, getting the data
from an external yaml file.
"""
class MockWrapper:
"""
Wraps all the data returned by the mocked function to behave like a
dictionary, like an object, like a function, like a jsonable dict...
like almost everything you may need
"""
def __init__(self, data):
self.__data = data
def __getattr__(self, key):
if key not in self.__data:
raise KeyError("'%s' not found in %s" % (key, self.__data.keys()))
return self.__getitem__(key)
def __call__(self):
return wrapped(self.__data)
def __getitem__(self, key):
val = self.__data[key]
if isinstance(val, (int, str)):
return val
return wrapped(val)
def __str__(self):
return str(self.__data)
def __repr__(self):
return repr(self.__data)
def __eq__(self, other):
return self.__data.__eq__(other)
def __le__(self, other):
return self.__data.__le__(other)
def __ge__(self, other):
return self.__data.__ge__(other)
def __lt__(self, other):
return self.__data.__lt__(other)
def __gt__(self, other):
return self.__data.__gt__(other)
def __len__(self):
return self.__data.__len__()
def keys(self):
return self.__data.keys()
def get(self, key, defv=None):
return self.__data.get(key, defv)
class MockWrapperList(MockWrapper, list):
def __init__(self, data):
MockWrapper.__init__(self, data)
list.__init__(self, data)
class MockWrapperDict(MockWrapper, dict):
def __init__(self, data):
MockWrapper.__init__(self, data)
dict.__init__(self, data)
def wrapped(data):
if isinstance(data, dict):
return MockWrapperDict(data)
if isinstance(data, list):
return MockWrapperList(data)
return MockWrapper(data)
def mock_match(A, B):
"""
Checked for params on a mocked function is as expected
It is necesary as sometimes we get a tuple and at the mock data we have
lists.
Examples:
```
>>> mock_match("A", "A")
True
>>> mock_match("A", "B")
False
>>> mock_match(["A", "B", "C"], ["A", "B", "C"])
True
>>> mock_match(["A", "B", "C"], "*")
True
```
"""
if B == '*': # always match
return True
if isinstance(A, (tuple, list)):
return all(mock_match(a, b) for (a, b) in zip(A, B))
return A == B
def mock_res(name, data, args=[], kwargs={}):
"""
Given a name, data and call parameters, returns the mocked response
If there is no matching response, raises an exception that can be used to
prepare the mock data.
This can be used for situations where you mock some function like data;
for example at [Serverboards](https://serverboards.io), we use it to
mock RPC calls.
Its also used internally on every other mocking.
"""
data = data.get(name)
if not data:
raise Exception(
"unknown method for mocking: \n%s:\n - args: %s\n kwargs: %s\n response: ...\n" % (
name, json.dumps(args), json.dumps(kwargs)
)
)
for res in data:
if (mock_match(args, res.get("args")) and
mock_match(kwargs, res.get("kwargs", {}))):
if 'error' in res:
raise Exception(res["error"])
response = res["response"]
if isinstance(response, (int, str)):
return response
return wrapped(response)
raise Exception(
"unknown data for mocking: \n%s:\n - args: %s\n kwargs: %s\n response: ...\n" % (
name, json.dumps(args), json.dumps(kwargs)
)
)
def mock_method(name, data):
"""
Returns a function that mocks an original function.
"""
def mockf(*args, **kwargs):
return mock_res(name, data, args, kwargs)
return mockf
def mock_method_async(name, data):
"""
Returns an async function that mocks an original async function
"""
async def mockf(*args, **kwargs):
return mock_res(name, data, args, kwargs)
return mockf
class SMock:
"""
Encapsulates mocking calls so it's easier to load data and mock methods
Example:
```python
>>> import requests
>>> smocked = SMock("tests/data.yaml")
>>> requests.get = smocked.mock_method("requests.get")
>>> res = requests.get("https://mocked.url")
>>> res.status_code
200
>>> res.content
'Gocha!'
>>> res.json()
{'text': 'Gocha too!'}
```
The mock file is a yaml file with each mocked function as keys, and
`args`/`kwargs` as calling args and kwargs, and `response` the response.
Check `tests/data.yaml` for an example at the source code.
"""
def __init__(self, mockfile):
with open(mockfile) as fd:
self._data = yaml.load(fd)
def mock_res(self, name, args=[], kwargs={}):
"""
Calls `mock_res`
Mock by args:
```
>>> smock = SMock("tests/data.yaml")
>>> res = smock.mock_res("requests.get", ["https://mocked.url"])
>>> res.status_code
200
```
Using "*" as args, as fallback. As there is no kwargs, use default:
```
>>> res = smock.mock_res("requests.get", ["https://error.mocked.url"])
>>> res.status_code
404
```
Using "*" as kwargs:
```
>>> res = smock.mock_res("requests.get",
... ["https://mocked.url"],
... {'data': 'data'})
>>> res.status_code
200
>>> res.content
'Mocked query'
```
"""
return mock_res(name, self._data, args, kwargs)
def mock_method(self, name):
"""
Calls `mock_method`
"""
return mock_method(name, self._data)
async def mock_method_async(self, name):
"""
Calls `mock_method_async`
"""
return await mock_method_async(name, self._data)