pytest-responsemock 2.0.0__py3-none-any.whl

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.
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.5
2
+ Name: pytest-responsemock
3
+ Version: 2.0.0
4
+ Summary: Simplified HTTP calls mocking for pytest (requests, httpx)
5
+ Project-URL: Homepage, https://github.com/idlesign/pytest-responsemock
6
+ Author-email: Igor Starikov <idlesign@yandex.ru>
7
+ License-Expression: BSD-3-Clause
8
+ License-File: LICENSE
9
+ Keywords: httpx,mock,pytest,requests
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Framework :: Pytest
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: BSD License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Testing
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: pytest
25
+ Requires-Dist: responses>=0.18.0
26
+ Requires-Dist: respx
27
+ Description-Content-Type: text/markdown
28
+
29
+ # pytest-responsemock
30
+
31
+ <https://github.com/idlesign/pytest-responsemock>
32
+
33
+ [![release](https://img.shields.io/pypi/v/pytest-responsemock.svg)](https://pypi.python.org/pypi/pytest-responsemock)
34
+ [![lic](https://img.shields.io/pypi/l/pytest-responsemock.svg)](https://pypi.python.org/pypi/pytest-responsemock)
35
+ [![coverage](https://img.shields.io/coveralls/idlesign/pytest-responsemock/master.svg)](https://coveralls.io/r/idlesign/pytest-responsemock)
36
+
37
+ ## Description
38
+
39
+ *Simplified HTTP calls mocking for pytest (requests, httpx)*
40
+
41
+ Provides `response_mock` fixture, exposing simple context manager.
42
+
43
+ Any request under that manager will be intercepted and mocked according
44
+ to one or more `rules` passed to the manager. If actual request won't fall
45
+ under any of given rules then an exception is raised (by default).
46
+
47
+ Rules are simple strings, of the pattern: `HTTP_METHOD URL -> STATUS_CODE :BODY`.
48
+
49
+ Requests made with both `requests` and `httpx` (sync and async clients) are intercepted.
50
+ Use the `backend` manager argument (`requests`/`httpx`/`all`) to select the backend,
51
+ or the `aresponse_mock` fixture as an `httpx`-oriented shortcut.
52
+
53
+ ## Requirements
54
+
55
+ * Python 3.10+
56
+
57
+ ## Usage
58
+
59
+ When this package is installed `response_mock` is available for `pytest` test functions.
60
+
61
+ ```python
62
+ def for_test():
63
+ return requests.get('http://some.domain')
64
+
65
+
66
+ def test_me(response_mock):
67
+
68
+ # Pass response rule as a string,
69
+ # or many rules (to mock consequent requests) as a list of strings/bytes.
70
+ # Use optional `bypass` argument to disable mock conditionally.
71
+
72
+ with response_mock('GET http://some.domain -> 200 :Nice', bypass=False):
73
+
74
+ result = for_test()
75
+
76
+ assert result.ok
77
+ assert result.content == b'Nice'
78
+
79
+ # mock consequent requests
80
+ with response_mock([
81
+ 'GET http://some.domain -> 200 :Nice',
82
+ 'GET http://other.domain -> 200 :Sweet',
83
+ ]):
84
+ for_test()
85
+ requests.get('http://other.domain')
86
+ ```
87
+
88
+ Use with `pytest-datafixtures`:
89
+
90
+ ```python
91
+ def test_me(response_mock, datafix_read):
92
+
93
+ with response_mock(f"GET http://some.domain -> 200 :{datafix_read('myresponse.html')}"):
94
+ ...
95
+ ```
96
+
97
+ Describe response header fields using multiline strings:
98
+
99
+ ```python
100
+ with response_mock(
101
+ '''
102
+ GET http://some.domain
103
+
104
+ Allow: GET, HEAD
105
+ Content-Language: ru
106
+
107
+ -> 200 :OK
108
+ '''
109
+ ):
110
+ ...
111
+ ```
112
+
113
+ Test json response:
114
+
115
+ ```python
116
+ response = json.dumps({'key': 'value', 'another': 'yes'})
117
+
118
+ with response_mock(f'POST http://some.domain -> 400 :{response}'):
119
+ ...
120
+ ```
121
+
122
+ To test binary response pass rule as bytes:
123
+
124
+ ```python
125
+ with response_mock(b'GET http://some.domain -> 200 :' + my_bytes):
126
+ ...
127
+ ```
128
+
129
+ Access underlying RequestsMock (from `responses` package) as `mock`:
130
+
131
+ ```python
132
+ with response_mock('HEAD http://some.domain -> 200 :Nope') as mock:
133
+
134
+ mock.add_passthru('http://other.domain')
135
+ ```
@@ -0,0 +1,8 @@
1
+ responsemock/__init__.py,sha256=T5tgdV1k7ZV4c92_yGKN6LcMCydL0BFA8kw_XeAOqew,18
2
+ responsemock/entry.py,sha256=gTpfIiz3gVDyu7XUgmwjfYOLIf6tZqqqDWq-5oD10Y0,1899
3
+ responsemock/utils.py,sha256=iGQ8jEIR8SOvErPxFyp53HK0ivpSf43nkCxWPkwKiI4,6178
4
+ pytest_responsemock-2.0.0.dist-info/METADATA,sha256=AiwmAqfTOgMIZy1kGUZP04w2u9cNwAOSSjP2PbqxKas,3977
5
+ pytest_responsemock-2.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ pytest_responsemock-2.0.0.dist-info/entry_points.txt,sha256=6pehqhhUWzGJcD2TdK3hKxGQoA-Nz0jWgwOz-XRmQX8,45
7
+ pytest_responsemock-2.0.0.dist-info/licenses/LICENSE,sha256=yqV7uolehVAdrDgUHsxY1pKjnLzRtdPborNeYgyD6Yg,1512
8
+ pytest_responsemock-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ responsemock = responsemock.entry
@@ -0,0 +1,28 @@
1
+ Copyright (c) 2020-2026, Igor `idle sign` Starikov
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the pytest-responsemock nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
@@ -0,0 +1 @@
1
+ VERSION = '2.0.0'
responsemock/entry.py ADDED
@@ -0,0 +1,70 @@
1
+ from functools import partial
2
+
3
+ import pytest
4
+
5
+ from .utils import response_mock as response_mock_
6
+
7
+
8
+ @pytest.fixture
9
+ def response_mock() -> response_mock_:
10
+ """Fixture exposing simple context manager to mock responses for `requests` and `httpx` packages.
11
+
12
+ Any request under that manager will be intercepted and mocked according
13
+ to one or more ``rules`` passed to the manager. If actual request won't fall
14
+ under any of given rules then an exception is raised (by default).
15
+
16
+ The backend is selected with the ``backend`` argument: ``requests`` (default)
17
+ intercepts `requests` only, ``httpx`` intercepts `httpx` (both sync and async
18
+ clients) only, ``all`` intercepts both.
19
+
20
+ Rules are simple strings, of pattern: ``HTTP_METHOD URL -> STATUS_CODE :BODY``.
21
+
22
+ Example::
23
+
24
+ def test_me(response_mock):
25
+
26
+
27
+ json_response = json.dumps({'key': 'value', 'another': 'yes'})
28
+
29
+ with response_mock([
30
+
31
+ 'GET http://a.b -> 200 :Nice',
32
+
33
+ f'POST http://some.domain -> 400 :{json_response}',
34
+
35
+ '''
36
+ GET https://some.domain
37
+
38
+ Allow: GET, HEAD
39
+ Content-Language: ru
40
+
41
+ -> 200 :OK
42
+ ''',
43
+
44
+ ], bypass=False) as mock:
45
+
46
+ mock.add_passthru('http://c.d')
47
+
48
+ this_mades_requests()
49
+
50
+
51
+ """
52
+ return response_mock_
53
+
54
+
55
+ @pytest.fixture
56
+ def aresponse_mock() -> response_mock_:
57
+ """Fixture exposing the same context manager as ``response_mock``,
58
+ but preset to intercept `httpx` only (both sync and async clients).
59
+
60
+ Example::
61
+
62
+ async def test_me(aresponse_mock):
63
+
64
+ with aresponse_mock('GET http://a.b -> 200 :Nice'):
65
+
66
+ async with httpx.AsyncClient() as client:
67
+ await client.get('http://a.b')
68
+
69
+ """
70
+ return partial(response_mock_, backend='httpx')
responsemock/utils.py ADDED
@@ -0,0 +1,218 @@
1
+ from contextlib import ExitStack, contextmanager
2
+ from textwrap import dedent
3
+ from typing import Any, Dict, Generator, List, Literal, Union
4
+
5
+ if False: # pragma: nocover
6
+ from responses import RequestsMock # noqa
7
+
8
+ TypeRule = Union[str, bytes]
9
+
10
+ TypeRuleParsed = Dict[str, Union[str, bytes, int, Dict[str, str]]]
11
+
12
+
13
+ def parse_rules(rules: Union[List[TypeRule], TypeRule]) -> List[TypeRuleParsed]:
14
+ """Parses rule strings into structured dicts.
15
+
16
+ Rules are simple strings, of pattern: ``HTTP_METHOD URL -> STATUS_CODE :BODY``.
17
+
18
+ :param rules: One or several rules for response.
19
+
20
+ """
21
+ parsed = []
22
+
23
+ if isinstance(rules, (str, bytes)):
24
+ rules = [rules]
25
+
26
+ for rule in rules:
27
+
28
+ if not rule:
29
+ continue
30
+
31
+ is_binary = isinstance(rule, bytes)
32
+
33
+ if not is_binary:
34
+ rule = dedent(rule)
35
+
36
+ rule = rule.strip()
37
+
38
+ type_ = bytes if is_binary else str
39
+ newline = b'\n' if is_binary else '\n'
40
+ colon = b':' if is_binary else ':'
41
+
42
+ def enc(val, binary=is_binary):
43
+ return val.encode() if binary else val
44
+
45
+ def dec(val, binary=is_binary):
46
+ return val.decode() if binary else val
47
+
48
+ directives, _, response = rule.partition(enc('->'))
49
+
50
+ headers = {}
51
+
52
+ if newline in directives:
53
+ directives, *headers_block = directives.splitlines()
54
+
55
+ for header_line in headers_block:
56
+ header_line = header_line.strip()
57
+
58
+ if not header_line:
59
+ continue
60
+
61
+ key, _, val = header_line.partition(colon)
62
+ val = val.strip()
63
+
64
+ if val:
65
+ headers[dec(key.strip())] = dec(val)
66
+
67
+ directives = list(
68
+ filter(
69
+ None,
70
+ map(
71
+ type_.strip,
72
+ directives.split(enc(' '))
73
+ )
74
+ ))
75
+
76
+ if len(directives) != 2:
77
+ raise ValueError(f'Unsupported directives: {directives}. Expected two entries: HTTP_METHOD and URL')
78
+
79
+ status, _, response = response.partition(colon)
80
+
81
+ parsed.append({
82
+ 'method': dec(directives[0]),
83
+ 'url': dec(directives[1]),
84
+ 'status': int(status.strip()),
85
+ 'headers': headers,
86
+ 'body': response,
87
+ })
88
+
89
+ return parsed
90
+
91
+
92
+ @contextmanager
93
+ def response_mock(
94
+ rules: Union[List[TypeRule], TypeRule],
95
+ *,
96
+ bypass: bool = False,
97
+ backend: Literal['requests', 'httpx', 'all'] = 'requests',
98
+ **kwargs
99
+ ) -> Generator[Any, None, None]:
100
+ """Simple context manager to mock responses for `requests` and `httpx` packages.
101
+
102
+ Any request under that manager will be intercepted and mocked according
103
+ to one or more ``rules`` passed to the manager. If actual request won't fall
104
+ under any of given rules then an exception is raised (by default).
105
+
106
+ Rules are simple strings, of pattern: ``HTTP_METHOD URL -> STATUS_CODE :BODY``.
107
+
108
+ Example::
109
+
110
+ def test_me(response_mock):
111
+
112
+
113
+ json_response = json.dumps({'key': 'value', 'another': 'yes'})
114
+
115
+ with response_mock([
116
+
117
+ 'GET http://a.b -> 200 :Nice',
118
+
119
+ b'GET http://a.b/binary/ -> 200 :\xd1\x82\xd0\xb5\xd1\x81\xd1\x82',
120
+
121
+ f'POST http://some.domain -> 400 :{json_response}'
122
+
123
+ '''
124
+ GET https://some.domain
125
+
126
+ Allow: GET, HEAD
127
+ Content-Language: ru
128
+
129
+ -> 200 :OK
130
+ '''
131
+
132
+ ], bypass=False) as mock:
133
+
134
+ mock.add_passthru('http://c.d')
135
+
136
+ this_makes_requests()
137
+
138
+ :param rules: One or several rules for response.
139
+ :param bypass: Whether to bypass (disable) mocking.
140
+ :param backend: Backend selection:
141
+
142
+ * ``requests`` (default) — intercept `requests` only;
143
+ * ``httpx`` — intercept `httpx` (both sync and async clients) only;
144
+ * ``all`` — intercept both.
145
+
146
+ Note that with both backends active the `assert_all_requests_are_fired`
147
+ option of ``RequestsMock`` defaults to ``False``, since rules may fire
148
+ through either of the two backends.
149
+
150
+ :param kwargs: Additional keyword arguments to pass to `RequestsMock`.
151
+
152
+ """
153
+ if bypass:
154
+
155
+ yield
156
+ return
157
+
158
+ parsed = parse_rules(rules)
159
+
160
+ use_requests = backend != 'httpx'
161
+ use_httpx = backend != 'requests'
162
+
163
+ if not (use_requests or use_httpx):
164
+ raise ValueError(f'Unsupported backend: {backend}')
165
+
166
+ with ExitStack() as stack:
167
+
168
+ mock = None
169
+
170
+ if use_requests:
171
+ from responses import RequestsMock
172
+
173
+ if use_httpx:
174
+ # With two active backends rules may fire through either of them,
175
+ # so the per-backend "all fired" assertion cannot hold.
176
+ kwargs.setdefault('assert_all_requests_are_fired', False)
177
+
178
+ mock = stack.enter_context(RequestsMock(**kwargs))
179
+
180
+ for rule in parsed:
181
+
182
+ headers = dict(rule['headers'])
183
+
184
+ add_kwargs = {}
185
+
186
+ content_type = headers.pop('Content-Type', None)
187
+
188
+ if content_type:
189
+ add_kwargs['content_type'] = content_type
190
+
191
+ mock.add(
192
+ method=rule['method'],
193
+ url=rule['url'],
194
+ body=rule['body'],
195
+ status=rule['status'],
196
+ adding_headers=headers or None,
197
+ **add_kwargs
198
+ )
199
+
200
+ if use_httpx:
201
+ import respx
202
+
203
+ router = stack.enter_context(respx.mock(
204
+ # Strictness is only possible when no other backend may serve the rules.
205
+ assert_all_called=not use_requests,
206
+ ))
207
+
208
+ for rule in parsed:
209
+ router.route(method=rule['method'], url=rule['url']).respond(
210
+ status_code=rule['status'],
211
+ content=rule['body'],
212
+ headers=rule['headers'] or None,
213
+ )
214
+
215
+ if mock is None:
216
+ mock = router
217
+
218
+ yield mock