-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfluent.py
More file actions
270 lines (228 loc) · 7.33 KB
/
Copy pathfluent.py
File metadata and controls
270 lines (228 loc) · 7.33 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#
# This file is part of the CloudBlue Connect Python OpenAPI Client.
#
# Copyright (c) 2025 CloudBlue. All Rights Reserved.
#
import json
import re
import httpx
import responses
from pytest import MonkeyPatch
from pytest_httpx import HTTPXMock
from pytest_httpx._options import _HTTPXMockOptions
from responses import matchers
from connect.client.fluent import _ConnectClientBase
from connect.client.testing.models import CollectionMock, NSMock
def body_matcher(body):
def match(request):
request_body = request.body
valid = body is None if request_body is None else body == request_body
if not valid:
return False, "%s doesn't match %s" % (request_body, body)
return valid, ''
return match
_mocker = responses.RequestsMock()
class ConnectClientMocker(_ConnectClientBase):
def __init__(self, base_url, exclude=None):
super().__init__('api_key', endpoint=base_url)
if exclude:
if not isinstance(exclude, (list, tuple, set)):
exclude = [exclude]
for item in exclude:
_mocker.add_passthru(item)
def get(
self,
url,
status_code=200,
return_value=None,
headers=None,
):
return self.mock(
'get',
url,
status_code=status_code,
return_value=return_value,
headers=headers,
)
def create(
self,
url,
status_code=201,
return_value=None,
headers=None,
match_body=None,
):
return self.mock(
'post',
url,
status_code=status_code,
return_value=return_value,
headers=headers,
match_body=match_body,
)
def update(
self,
url,
status_code=201,
return_value=None,
headers=None,
match_body=None,
):
return self.mock(
'put',
url,
status_code=status_code,
return_value=return_value,
headers=headers,
match_body=match_body,
)
def delete(
self,
url,
status_code=204,
return_value=None,
headers=None,
match_body=None,
):
return self.mock(
'delete',
url,
status_code=status_code,
return_value=return_value,
headers=headers,
match_body=match_body,
)
def mock(
self,
method,
path,
status_code=200,
return_value=None,
headers=None,
match_body=None,
):
url = f'{self.endpoint}/{path}'
kwargs = {
'method': method.upper(),
'url': url,
'status': status_code,
'headers': headers,
}
if isinstance(return_value, (dict, list, tuple)):
kwargs['json'] = return_value
else:
kwargs['body'] = return_value
if match_body:
if isinstance(match_body, (dict, list, tuple)):
kwargs['match'] = [
matchers.json_params_matcher(match_body),
]
else:
kwargs['match'] = [
body_matcher(match_body),
]
_mocker.add(**kwargs)
def start(self):
_mocker.start()
def reset(self, success=True):
try:
_mocker.stop(allow_assert=success)
finally:
_mocker.reset()
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, value, traceback):
self.reset(success=exc_type is None)
def _get_collection_class(self):
return CollectionMock
def _get_namespace_class(self):
return NSMock
_monkeypatch = MonkeyPatch()
# The ConnectClient retries requests, so a single registered response must be
# able to answer repeated (retried) requests.
_async_mocker = HTTPXMock(
_HTTPXMockOptions(
can_send_already_matched_responses=True,
),
)
class AsyncConnectClientMocker(ConnectClientMocker):
def __init__(self, base_url, exclude=None):
super().__init__(base_url)
self.exclude = exclude or []
def start(self):
patterns = self.exclude if isinstance(self.exclude, (list, tuple, set)) else [self.exclude]
real_handle_async_request = httpx.AsyncHTTPTransport.handle_async_request
async def mocked_handle_async_request(
transport: httpx.AsyncHTTPTransport, request: httpx.Request
) -> httpx.Response:
for pattern in patterns:
if (isinstance(pattern, re.Pattern) and pattern.match(str(request.url))) or (
isinstance(pattern, str) and str(request.url).startswith(pattern)
):
return await real_handle_async_request(transport, request)
return await _async_mocker._handle_async_request(transport, request)
_monkeypatch.setattr(
httpx.AsyncHTTPTransport,
"handle_async_request",
mocked_handle_async_request,
)
def reset(self, success=True):
try:
if success:
# pytest-httpx>=0.31 no longer asserts on reset(); do it explicitly
# so unrequested mocks / unexpected requests still fail the test.
_async_mocker._assert_options()
finally:
_async_mocker.reset()
_monkeypatch.undo()
def mock(
self,
method,
path,
status_code=200,
return_value=None,
headers=None,
match_body=None,
):
url = f'{self.endpoint}/{path}'
kwargs = {
'method': method.upper(),
'url': url,
'status_code': status_code,
'headers': headers,
}
if isinstance(return_value, (dict, list, tuple)):
kwargs['json'] = return_value
else:
kwargs['content'] = return_value.encode() if return_value else None
if match_body:
if isinstance(match_body, (dict, list, tuple)):
# Mirror httpx>=0.28's request-body serialization exactly, or
# match_content won't compare equal (compact separators, raw
# UTF-8 rather than \uXXXX escapes, and no NaN/Infinity).
kwargs['match_content'] = json.dumps(
match_body,
separators=(',', ':'),
ensure_ascii=False,
allow_nan=False,
).encode('utf-8')
else:
kwargs['match_content'] = match_body
_async_mocker.add_response(**kwargs)
def get_requests_mocker():
"""
Returns a mocker object to mock http calls made using the `requests` library
when they are made in conjunction with calls made with the `ConnectClient`.
The returned mocker is the one provided by the
[responses](https://github.com/getsentry/responses) library.
"""
return _mocker
def get_httpx_mocker():
"""
Returns a mocker object to mock http calls made using the `httpx` library
when they are made in conjunction with calls made with the `AsyncConnectClient`.
The returned mocker is the one provided by the
[pytest-httpx](https://colin-b.github.io/pytest_httpx/) library.
"""
return _async_mocker