friendrequest 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (60) hide show
  1. {friendrequest-0.2.0 → friendrequest-0.3.0}/PKG-INFO +1 -1
  2. friendrequest-0.3.0/src/friendrequest/call.py +17 -0
  3. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/expectations/__init__.py +2 -0
  4. friendrequest-0.3.0/src/friendrequest/expectations/call_expectations.py +53 -0
  5. friendrequest-0.3.0/src/friendrequest/expectations/host_expectations.py +207 -0
  6. friendrequest-0.3.0/src/friendrequest/expected_response.py +12 -0
  7. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/friendrequest_class.py +14 -10
  8. friendrequest-0.3.0/src/friendrequest/response.py +51 -0
  9. friendrequest-0.3.0/tests/expectations/test_call_expectations.py +118 -0
  10. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/expectations/test_host_expectations.py +54 -1
  11. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/queries/test_call.py +15 -0
  12. friendrequest-0.3.0/tests/test_call.py +26 -0
  13. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/test_friendrequest_expectations.py +80 -1
  14. friendrequest-0.3.0/tests/test_response.py +110 -0
  15. friendrequest-0.2.0/src/friendrequest/call.py +0 -12
  16. friendrequest-0.2.0/src/friendrequest/expectations/host_expectations.py +0 -82
  17. {friendrequest-0.2.0 → friendrequest-0.3.0}/.editorconfig +0 -0
  18. {friendrequest-0.2.0 → friendrequest-0.3.0}/.github/workflows/check.yml +0 -0
  19. {friendrequest-0.2.0 → friendrequest-0.3.0}/.github/workflows/release.yml +0 -0
  20. {friendrequest-0.2.0 → friendrequest-0.3.0}/.gitignore +0 -0
  21. {friendrequest-0.2.0 → friendrequest-0.3.0}/.python-version +0 -0
  22. {friendrequest-0.2.0 → friendrequest-0.3.0}/.vscode/settings.json +0 -0
  23. {friendrequest-0.2.0 → friendrequest-0.3.0}/CONTRIBUTING.md +0 -0
  24. {friendrequest-0.2.0 → friendrequest-0.3.0}/LICENSE +0 -0
  25. {friendrequest-0.2.0 → friendrequest-0.3.0}/README.md +0 -0
  26. {friendrequest-0.2.0 → friendrequest-0.3.0}/mise.lock +0 -0
  27. {friendrequest-0.2.0 → friendrequest-0.3.0}/mise.toml +0 -0
  28. {friendrequest-0.2.0 → friendrequest-0.3.0}/pyproject.toml +0 -0
  29. {friendrequest-0.2.0 → friendrequest-0.3.0}/rumdl.toml +0 -0
  30. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/__init__.py +0 -0
  31. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/auth.py +0 -0
  32. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/exceptions/__init__.py +0 -0
  33. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/exceptions/unexpected_request.py +0 -0
  34. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/expectations/global_expectations.py +0 -0
  35. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/headers.py +0 -0
  36. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/py.typed +0 -0
  37. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/queries/__init__.py +0 -0
  38. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/queries/call.py +0 -0
  39. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/queries/headers.py +0 -0
  40. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/queries/request.py +0 -0
  41. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/request.py +0 -0
  42. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/rules/__init__.py +0 -0
  43. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/rules/global_rules.py +0 -0
  44. {friendrequest-0.2.0 → friendrequest-0.3.0}/src/friendrequest/rules/host_rules.py +0 -0
  45. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/__init__.py +0 -0
  46. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/exceptions/__init__.py +0 -0
  47. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/exceptions/test_unexpected_request.py +0 -0
  48. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/expectations/__init__.py +0 -0
  49. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/queries/__init__.py +0 -0
  50. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/queries/test_headers.py +0 -0
  51. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/queries/test_request.py +0 -0
  52. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/request_helpers.py +0 -0
  53. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/rules/__init__.py +0 -0
  54. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/rules/test_global_rules.py +0 -0
  55. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/test_auth.py +0 -0
  56. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/test_friendrequest_class.py +0 -0
  57. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/test_headers.py +0 -0
  58. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/test_init.py +0 -0
  59. {friendrequest-0.2.0 → friendrequest-0.3.0}/tests/test_request.py +0 -0
  60. {friendrequest-0.2.0 → friendrequest-0.3.0}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: friendrequest
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: A friendly requests test helper.
5
5
  Project-URL: Repository, https://github.com/cariad/friendrequest
6
6
  Author-email: Cariad Eccleston <cariad@cariad.earth>
@@ -0,0 +1,17 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ from .expected_response import ExpectedResponse
4
+
5
+
6
+ @dataclass
7
+ class Call:
8
+ """A request call."""
9
+
10
+ method: str
11
+ """Upper-case HTTP method of the request's call."""
12
+
13
+ response: ExpectedResponse = field(default_factory=ExpectedResponse, kw_only=True)
14
+ """Response to the call."""
15
+
16
+ url: str
17
+ """URL of the request's call."""
@@ -1,7 +1,9 @@
1
+ from .call_expectations import CallExpectations
1
2
  from .global_expectations import GlobalExpectations
2
3
  from .host_expectations import HostExpectations
3
4
 
4
5
  __all__ = [
6
+ "CallExpectations",
5
7
  "GlobalExpectations",
6
8
  "HostExpectations",
7
9
  ]
@@ -0,0 +1,53 @@
1
+ import json
2
+ from typing import Any
3
+
4
+ from ..call import Call
5
+ from ..expected_response import ExpectedResponse
6
+
7
+ _NO_BODY: Any = object()
8
+ """Default `body` of `CallExpectations.with_response`, describing no body."""
9
+
10
+
11
+ class CallExpectations:
12
+ """Expectations of a specific request call."""
13
+
14
+ def __init__(self, call: Call) -> None:
15
+ """
16
+ Initialise the call expectations.
17
+
18
+ Args:
19
+ call: Call to record the expectations in.
20
+ """
21
+
22
+ self._call = call
23
+ """Call to record the expectations in."""
24
+
25
+ def with_response(
26
+ self,
27
+ *,
28
+ body: Any = _NO_BODY,
29
+ status: int = 200,
30
+ ) -> None:
31
+ """
32
+ Describe the response to this call.
33
+
34
+ A call that's never described gets the same response as one described with no
35
+ arguments.
36
+
37
+ Args:
38
+ body: JSON-serialisable body. Defaults to no body. `None` is JSON `null`.
39
+ status: HTTP status code.
40
+
41
+ Raises:
42
+ TypeError: The body isn't JSON-serialisable.
43
+ ValueError: The body isn't JSON-serialisable.
44
+ """
45
+
46
+ # Encoding now reports a body that can't be encoded to the test rather than to
47
+ # the code under test, and ignores any later changes to the body.
48
+ content = b"" if body is _NO_BODY else json.dumps(body).encode()
49
+
50
+ self._call.response = ExpectedResponse(
51
+ content=content,
52
+ status=status,
53
+ )
@@ -0,0 +1,207 @@
1
+ from urllib.parse import urlsplit
2
+
3
+ from ..call import Call
4
+ from ..request import prepare_request
5
+ from ..rules import GlobalRules, HostRules
6
+ from .call_expectations import CallExpectations
7
+
8
+
9
+ class HostExpectations:
10
+ """Expectations of requests to a specific host."""
11
+
12
+ def __init__(
13
+ self,
14
+ name: str,
15
+ rules: GlobalRules,
16
+ ) -> None:
17
+ """
18
+ Initialise the host expectations.
19
+
20
+ Args:
21
+ name: Case-insensitive host name, like `example.com`.
22
+ rules: Global rules to record this host's expectations in.
23
+
24
+ Raises:
25
+ requests.RequestException: `requests` couldn't prepare a URL for the host.
26
+ ValueError: The name isn't only a host name.
27
+ """
28
+
29
+ url = prepare_request("GET", f"https://{name}/").url
30
+
31
+ if urlsplit(str(url)).hostname != name.lower():
32
+ raise ValueError(f"expected {name!r} to be only a host name")
33
+
34
+ self._host_rules = rules.hosts.setdefault(name, HostRules())
35
+ """Rules to record this host's own expectations in."""
36
+
37
+ self._name = name
38
+ """Host name."""
39
+
40
+ self._rules = rules
41
+ """Rules to record this host's expected calls in, in order with every host's."""
42
+
43
+ def call(
44
+ self,
45
+ method: str,
46
+ path: str,
47
+ ) -> CallExpectations:
48
+ """
49
+ Expect a request call to this host, over HTTPS.
50
+
51
+ Args:
52
+ method: HTTP method.
53
+ path: Path on this host, starting with a slash, like `/users/me`.
54
+
55
+ Returns:
56
+ The call's expectations.
57
+
58
+ Raises:
59
+ requests.RequestException: `requests` couldn't prepare the call's URL.
60
+ ValueError: The path doesn't start with a slash.
61
+ """
62
+
63
+ if not path.startswith("/"):
64
+ raise ValueError(f"expected path {path!r} to start with '/'")
65
+
66
+ # Preparing normalises the method and URL just like a request's call is, so the
67
+ # two can be compared.
68
+ request = prepare_request(method, f"https://{self._name}{path}")
69
+
70
+ call = Call(
71
+ method=str(request.method),
72
+ url=str(request.url),
73
+ )
74
+
75
+ self._rules.calls.append(call)
76
+
77
+ return CallExpectations(call)
78
+
79
+ def delete(self, path: str) -> CallExpectations:
80
+ """
81
+ Expect a DELETE request call to this host, over HTTPS.
82
+
83
+ Args:
84
+ path: Path on this host, starting with a slash, like `/users/me`.
85
+
86
+ Returns:
87
+ The call's expectations.
88
+
89
+ Raises:
90
+ requests.RequestException: `requests` couldn't prepare the call's URL.
91
+ ValueError: The path doesn't start with a slash.
92
+ """
93
+
94
+ return self.call("DELETE", path)
95
+
96
+ def get(self, path: str) -> CallExpectations:
97
+ """
98
+ Expect a GET request call to this host, over HTTPS.
99
+
100
+ Args:
101
+ path: Path on this host, starting with a slash, like `/users/me`.
102
+
103
+ Returns:
104
+ The call's expectations.
105
+
106
+ Raises:
107
+ requests.RequestException: `requests` couldn't prepare the call's URL.
108
+ ValueError: The path doesn't start with a slash.
109
+ """
110
+
111
+ return self.call("GET", path)
112
+
113
+ def head(self, path: str) -> CallExpectations:
114
+ """
115
+ Expect a HEAD request call to this host, over HTTPS.
116
+
117
+ Args:
118
+ path: Path on this host, starting with a slash, like `/users/me`.
119
+
120
+ Returns:
121
+ The call's expectations.
122
+
123
+ Raises:
124
+ requests.RequestException: `requests` couldn't prepare the call's URL.
125
+ ValueError: The path doesn't start with a slash.
126
+ """
127
+
128
+ return self.call("HEAD", path)
129
+
130
+ def header(self, name: str, value: str) -> None:
131
+ """
132
+ Expect a header on every request to this host.
133
+
134
+ Args:
135
+ name: Case-insensitive header name.
136
+ value: Header value.
137
+ """
138
+
139
+ self._host_rules.headers[name] = value
140
+
141
+ def options(self, path: str) -> CallExpectations:
142
+ """
143
+ Expect an OPTIONS request call to this host, over HTTPS.
144
+
145
+ Args:
146
+ path: Path on this host, starting with a slash, like `/users/me`.
147
+
148
+ Returns:
149
+ The call's expectations.
150
+
151
+ Raises:
152
+ requests.RequestException: `requests` couldn't prepare the call's URL.
153
+ ValueError: The path doesn't start with a slash.
154
+ """
155
+
156
+ return self.call("OPTIONS", path)
157
+
158
+ def patch(self, path: str) -> CallExpectations:
159
+ """
160
+ Expect a PATCH request call to this host, over HTTPS.
161
+
162
+ Args:
163
+ path: Path on this host, starting with a slash, like `/users/me`.
164
+
165
+ Returns:
166
+ The call's expectations.
167
+
168
+ Raises:
169
+ requests.RequestException: `requests` couldn't prepare the call's URL.
170
+ ValueError: The path doesn't start with a slash.
171
+ """
172
+
173
+ return self.call("PATCH", path)
174
+
175
+ def post(self, path: str) -> CallExpectations:
176
+ """
177
+ Expect a POST request call to this host, over HTTPS.
178
+
179
+ Args:
180
+ path: Path on this host, starting with a slash, like `/users/me`.
181
+
182
+ Returns:
183
+ The call's expectations.
184
+
185
+ Raises:
186
+ requests.RequestException: `requests` couldn't prepare the call's URL.
187
+ ValueError: The path doesn't start with a slash.
188
+ """
189
+
190
+ return self.call("POST", path)
191
+
192
+ def put(self, path: str) -> CallExpectations:
193
+ """
194
+ Expect a PUT request call to this host, over HTTPS.
195
+
196
+ Args:
197
+ path: Path on this host, starting with a slash, like `/users/me`.
198
+
199
+ Returns:
200
+ The call's expectations.
201
+
202
+ Raises:
203
+ requests.RequestException: `requests` couldn't prepare the call's URL.
204
+ ValueError: The path doesn't start with a slash.
205
+ """
206
+
207
+ return self.call("PUT", path)
@@ -0,0 +1,12 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(frozen=True)
5
+ class ExpectedResponse:
6
+ """A response to an expected call."""
7
+
8
+ content: bytes = b""
9
+ """JSON-encoded body of the response, or empty for no body."""
10
+
11
+ status: int = 200
12
+ """HTTP status code of the response."""
@@ -5,6 +5,7 @@ import requests
5
5
  from .expectations import GlobalExpectations
6
6
  from .queries import assert_request_is_expected
7
7
  from .request import prepare_request
8
+ from .response import make_response
8
9
  from .rules import GlobalRules
9
10
 
10
11
  _UNSUPPORTED = {
@@ -26,7 +27,8 @@ class FriendRequest:
26
27
  A friendly stand-in for the `requests` module in code under test.
27
28
 
28
29
  Important! `friendrequest` is in early development. Calls can be expected by
29
- method and path only so far, and every expected call gets an empty 200 response.
30
+ method and path only so far, and responses can be described by status and JSON
31
+ body only.
30
32
 
31
33
  Example:
32
34
  Create a `FriendRequest`, then patch it over the `requests` module as imported
@@ -39,8 +41,12 @@ class FriendRequest:
39
41
  from my_package.my_module import my_function
40
42
 
41
43
  requests = FriendRequest()
44
+
42
45
  requests.expect.header("Authorization", "my-api-key")
43
- requests.expect.host("example.com").call("GET", "/me")
46
+
47
+ requests.expect.host("example.com").get("/me").with_response(
48
+ body={"name": "Alice"},
49
+ )
44
50
 
45
51
  with patch("my_package.my_module.requests", requests):
46
52
  my_function()
@@ -295,12 +301,10 @@ class FriendRequest:
295
301
  request = prepare_request(method, url, **kwargs)
296
302
  assert_request_is_expected(request, self._rules)
297
303
 
298
- self._rules.calls.pop(0)
304
+ call = self._rules.calls.pop(0)
299
305
 
300
- # Responses can't be described yet, so every expected call gets an empty one.
301
- response = requests.Response()
302
- response.request = request
303
- response.status_code = 200
304
- response.url = str(request.url)
305
-
306
- return response
306
+ return make_response(
307
+ request,
308
+ call.response,
309
+ stream=bool(kwargs.get("stream")),
310
+ )
@@ -0,0 +1,51 @@
1
+ from http.client import responses
2
+ from io import BytesIO
3
+
4
+ import requests
5
+ from urllib3 import HTTPResponse
6
+
7
+ from .expected_response import ExpectedResponse
8
+
9
+
10
+ def make_response(
11
+ request: requests.PreparedRequest,
12
+ expected: ExpectedResponse,
13
+ *,
14
+ stream: bool = False,
15
+ ) -> requests.Response:
16
+ """
17
+ Make the response that `requests.request` would return for an expected call.
18
+
19
+ Args:
20
+ request: Request to respond to.
21
+ expected: Response to make.
22
+ stream: Leave the content unread, like `requests` does when asked to stream.
23
+
24
+ Returns:
25
+ The response, with its content already read unless it's streamed.
26
+ """
27
+
28
+ response = requests.Response()
29
+ response.encoding = "utf-8"
30
+
31
+ if expected.content:
32
+ response.headers["Content-Type"] = "application/json"
33
+
34
+ response.raw = HTTPResponse(
35
+ body=BytesIO(expected.content),
36
+ headers=response.headers,
37
+ preload_content=False,
38
+ status=expected.status,
39
+ )
40
+
41
+ response.reason = responses.get(expected.status, "")
42
+ response.request = request
43
+ response.status_code = expected.status
44
+ response.url = str(request.url)
45
+
46
+ # Read the content now, like `requests` does unless it's asked to stream, so the
47
+ # response can still be read after it's closed.
48
+ if not stream:
49
+ _ = response.content
50
+
51
+ return response
@@ -0,0 +1,118 @@
1
+ from typing import Any
2
+
3
+ from pytest import mark, raises
4
+
5
+ from friendrequest.call import Call
6
+ from friendrequest.expectations import CallExpectations
7
+ from friendrequest.expected_response import ExpectedResponse
8
+
9
+
10
+ def make_call() -> Call:
11
+ """
12
+ Make a GET call to https://example.com/.
13
+
14
+ Returns:
15
+ A call.
16
+ """
17
+
18
+ return Call("GET", "https://example.com/")
19
+
20
+
21
+ def test_with_response_defaults() -> None:
22
+ """Test that a response described with no arguments is the default response."""
23
+
24
+ call = make_call()
25
+
26
+ CallExpectations(call).with_response()
27
+
28
+ assert call == make_call()
29
+ assert call.response == ExpectedResponse(content=b"", status=200)
30
+
31
+
32
+ @mark.parametrize(
33
+ ("body", "expect"),
34
+ [
35
+ ({"foo": "bar"}, b'{"foo": "bar"}'),
36
+ ({}, b"{}"),
37
+ (None, b"null"),
38
+ ([1, 2], b"[1, 2]"),
39
+ ("foo", b'"foo"'),
40
+ ({"foo": "bär"}, b'{"foo": "b\\u00e4r"}'),
41
+ ],
42
+ )
43
+ def test_with_response_encodes_body(body: Any, expect: bytes) -> None:
44
+ """Test that a described body is recorded as JSON."""
45
+
46
+ call = make_call()
47
+
48
+ CallExpectations(call).with_response(body=body)
49
+
50
+ assert call.response == ExpectedResponse(content=expect)
51
+
52
+
53
+ def test_with_response_ignores_later_changes_to_body() -> None:
54
+ """Test that changing a body after describing it doesn't change the response."""
55
+
56
+ body = {"foo": "bar"}
57
+ call = make_call()
58
+
59
+ CallExpectations(call).with_response(body=body)
60
+ body["foo"] = "baz"
61
+
62
+ assert call.response.content == b'{"foo": "bar"}'
63
+
64
+
65
+ def test_with_response_records_status() -> None:
66
+ """Test that a described status is recorded with the default body."""
67
+
68
+ call = make_call()
69
+
70
+ CallExpectations(call).with_response(status=404)
71
+
72
+ assert call.response == ExpectedResponse(status=404)
73
+
74
+
75
+ @mark.parametrize(
76
+ ("body", "error_type"),
77
+ [
78
+ ({"foo": {1, 2}}, TypeError),
79
+ (b"foo", TypeError),
80
+ ],
81
+ )
82
+ def test_with_response_rejects_unserialisable_body(
83
+ body: Any,
84
+ error_type: type[Exception],
85
+ ) -> None:
86
+ """Test that a body that can't be JSON-encoded is rejected when it's described."""
87
+
88
+ call = make_call()
89
+
90
+ with raises(error_type):
91
+ CallExpectations(call).with_response(body=body, status=404)
92
+
93
+ assert call.response == ExpectedResponse()
94
+
95
+
96
+ def test_with_response_rejects_circular_body() -> None:
97
+ """Test that a body that refers to itself is rejected when it's described."""
98
+
99
+ body: dict[str, Any] = {}
100
+ body["self"] = body
101
+ call = make_call()
102
+
103
+ with raises(ValueError):
104
+ CallExpectations(call).with_response(body=body)
105
+
106
+ assert call.response == ExpectedResponse()
107
+
108
+
109
+ def test_with_response_twice_replaces_response() -> None:
110
+ """Test that describing a response again replaces the whole description."""
111
+
112
+ call = make_call()
113
+ expectations = CallExpectations(call)
114
+
115
+ expectations.with_response(status=404)
116
+ expectations.with_response(body={"foo": "bar"})
117
+
118
+ assert call.response == ExpectedResponse(content=b'{"foo": "bar"}', status=200)
@@ -2,7 +2,8 @@ import requests
2
2
  from pytest import mark, raises
3
3
 
4
4
  from friendrequest.call import Call
5
- from friendrequest.expectations import HostExpectations
5
+ from friendrequest.expectations import CallExpectations, HostExpectations
6
+ from friendrequest.expected_response import ExpectedResponse
6
7
  from friendrequest.rules import GlobalRules
7
8
 
8
9
 
@@ -145,3 +146,55 @@ def test_shares_rules_with_same_host_whatever_the_case() -> None:
145
146
 
146
147
  assert len(rules.hosts) == 1
147
148
  assert rules.hosts["example.com"].headers == expect
149
+
150
+
151
+ def test_call_returns_expectations_of_the_recorded_call() -> None:
152
+ """Test that the returned expectations record in the expected call."""
153
+
154
+ rules = GlobalRules()
155
+
156
+ HostExpectations("example.com", rules).call("GET", "/a").with_response(status=404)
157
+
158
+ expect = [
159
+ Call(
160
+ "GET",
161
+ "https://example.com/a",
162
+ response=ExpectedResponse(status=404),
163
+ ),
164
+ ]
165
+
166
+ assert rules.calls == expect
167
+
168
+
169
+ @mark.parametrize(
170
+ "function",
171
+ [
172
+ "delete",
173
+ "get",
174
+ "head",
175
+ "options",
176
+ "patch",
177
+ "post",
178
+ "put",
179
+ ],
180
+ )
181
+ def test_method_function_expects_call(function: str) -> None:
182
+ """Test that each HTTP method function expects a call with its method."""
183
+
184
+ rules = GlobalRules()
185
+
186
+ expectations = getattr(HostExpectations("example.com", rules), function)("/a")
187
+
188
+ assert isinstance(expectations, CallExpectations)
189
+ assert rules.calls == [Call(function.upper(), "https://example.com/a")]
190
+
191
+
192
+ def test_method_function_rejects_path_without_leading_slash() -> None:
193
+ """Test that an HTTP method function holds its path to the same rule as `call`."""
194
+
195
+ rules = GlobalRules()
196
+
197
+ with raises(ValueError):
198
+ HostExpectations("example.com", rules).get("a")
199
+
200
+ assert rules.calls == []
@@ -1,4 +1,5 @@
1
1
  from friendrequest.call import Call
2
+ from friendrequest.expected_response import ExpectedResponse
2
3
  from friendrequest.queries import get_call_problems
3
4
  from tests.request_helpers import make_request
4
5
 
@@ -37,6 +38,20 @@ def test_out_of_order() -> None:
37
38
  assert get_call_problems(request, calls) == expect
38
39
 
39
40
 
41
+ def test_response_is_not_compared() -> None:
42
+ """Test that a call's response doesn't affect whether a request is expected."""
43
+
44
+ calls = [
45
+ Call(
46
+ "GET",
47
+ "https://example.com/",
48
+ response=ExpectedResponse(status=404),
49
+ ),
50
+ ]
51
+
52
+ assert get_call_problems(make_request(), calls) == []
53
+
54
+
40
55
  def test_wrong_method() -> None:
41
56
  """Test that a request with another method isn't the next expected call."""
42
57
 
@@ -0,0 +1,26 @@
1
+ from pytest import raises
2
+
3
+ from friendrequest.call import Call
4
+ from friendrequest.expected_response import ExpectedResponse
5
+
6
+
7
+ def test_response_defaults() -> None:
8
+ """Test that a call gets the default response unless it's given one."""
9
+
10
+ assert Call("GET", "https://example.com/").response == ExpectedResponse()
11
+
12
+
13
+ def test_response_is_compared() -> None:
14
+ """Test that calls with different responses aren't equal."""
15
+
16
+ a = Call("GET", "https://example.com/")
17
+ b = Call("GET", "https://example.com/", response=ExpectedResponse(status=404))
18
+
19
+ assert a != b
20
+
21
+
22
+ def test_response_is_keyword_only() -> None:
23
+ """Test that a call's response can't be passed by position."""
24
+
25
+ with raises(TypeError):
26
+ Call("GET", "https://example.com/", ExpectedResponse()) # type: ignore[call-arg]
@@ -20,7 +20,7 @@ def test_basic_auth_header_is_seen() -> None:
20
20
 
21
21
 
22
22
  def test_call() -> None:
23
- """Test that an expected call gets an empty 200 response."""
23
+ """Test that an expected call gets a 200 response with no body."""
24
24
 
25
25
  fr = FriendRequest()
26
26
 
@@ -29,6 +29,7 @@ def test_call() -> None:
29
29
  response = fr.get("https://example.com/profile")
30
30
 
31
31
  assert response.status_code == 200
32
+ assert response.content == b""
32
33
  assert response.url == "https://example.com/profile"
33
34
  assert response.request.method == "GET"
34
35
 
@@ -63,6 +64,49 @@ def test_call_to_other_host() -> None:
63
64
  assert ex.value.problem == "expected GET https://example.com/profile next"
64
65
 
65
66
 
67
+ def test_call_with_response() -> None:
68
+ """Test that an expected call gets the response it's described with."""
69
+
70
+ fr = FriendRequest()
71
+
72
+ fr.expect.host("api.bunny.net").get("/dnszone/123").with_response(
73
+ status=200,
74
+ body={"foo": "bar"},
75
+ )
76
+
77
+ response = fr.get("https://api.bunny.net/dnszone/123")
78
+
79
+ assert response.status_code == 200
80
+ assert response.json() == {"foo": "bar"}
81
+
82
+
83
+ def test_call_with_response_without_arguments() -> None:
84
+ """Test that a response described with no arguments is the default response."""
85
+
86
+ fr = FriendRequest()
87
+
88
+ fr.expect.host("example.com").get("/a")
89
+ fr.expect.host("example.com").get("/b").with_response()
90
+
91
+ a = fr.get("https://example.com/a")
92
+ b = fr.get("https://example.com/b")
93
+
94
+ assert (a.status_code, a.content, a.headers) == (200, b"", b.headers)
95
+ assert (b.status_code, b.content) == (200, b"")
96
+
97
+
98
+ def test_call_with_stream() -> None:
99
+ """Test that a streamed call's response is left unread."""
100
+
101
+ fr = FriendRequest()
102
+
103
+ fr.expect.host("example.com").get("/a").with_response(body={"a": 1})
104
+
105
+ response = fr.get("https://example.com/a", stream=True)
106
+
107
+ assert response.raw.read() == b'{"a": 1}'
108
+
109
+
66
110
  def test_call_with_unmet_header() -> None:
67
111
  """Test that an expected call must still carry the expected headers."""
68
112
 
@@ -85,6 +129,28 @@ def test_call_with_unmet_header() -> None:
85
129
  assert response.status_code == 200
86
130
 
87
131
 
132
+ def test_calls_get_their_own_responses() -> None:
133
+ """Test that each expected call gets its own response, in order."""
134
+
135
+ fr = FriendRequest()
136
+
137
+ host = fr.expect.host("example.com")
138
+ host.post("/token").with_response(status=201, body={"token": "abc"})
139
+ host.get("/profile").with_response(status=404, body={"error": "gone"})
140
+ host.delete("/token")
141
+
142
+ token = fr.post("https://example.com/token")
143
+ profile = fr.get("https://example.com/profile")
144
+ deleted = fr.delete("https://example.com/token")
145
+
146
+ assert (token.status_code, token.json()) == (201, {"token": "abc"})
147
+ assert (profile.status_code, profile.json()) == (404, {"error": "gone"})
148
+ assert (deleted.status_code, deleted.content) == (200, b"")
149
+
150
+ with raises(fr.HTTPError):
151
+ profile.raise_for_status()
152
+
153
+
88
154
  def test_calls_in_order() -> None:
89
155
  """Test that expected calls can be made in the order that they're expected."""
90
156
 
@@ -249,3 +315,16 @@ def test_patched_over_requests() -> None:
249
315
 
250
316
  assert ex.value.problem == "expected header 'Authorization' but saw none"
251
317
  assert response.status_code == 200
318
+
319
+
320
+ def test_unexpected_request_does_not_use_up_response() -> None:
321
+ """Test that a failed request leaves the expected call's response to be given."""
322
+
323
+ fr = FriendRequest()
324
+
325
+ fr.expect.host("example.com").get("/a").with_response(body={"a": 1})
326
+
327
+ with raises(UnexpectedRequest):
328
+ fr.get("https://example.com/b")
329
+
330
+ assert fr.get("https://example.com/a").json() == {"a": 1}
@@ -0,0 +1,110 @@
1
+ import requests
2
+ from pytest import mark, raises
3
+
4
+ from friendrequest.expected_response import ExpectedResponse
5
+ from friendrequest.response import make_response
6
+ from tests.request_helpers import make_request
7
+
8
+
9
+ def test_make_response_content() -> None:
10
+ """Test that `make_response` gives the expected content as a JSON body."""
11
+
12
+ expected = ExpectedResponse(content=b'{"foo": "b\\u00e4r"}')
13
+
14
+ response = make_response(make_request(), expected)
15
+
16
+ assert response.content == b'{"foo": "b\\u00e4r"}'
17
+ assert response.text == '{"foo": "b\\u00e4r"}'
18
+ assert response.json() == {"foo": "bär"}
19
+ assert response.encoding == "utf-8"
20
+ assert response.headers == {"content-type": "application/json"}
21
+
22
+
23
+ def test_make_response_content_is_already_read() -> None:
24
+ """Test that `make_response` reads the content like an unstreamed request."""
25
+
26
+ response = make_response(make_request(), ExpectedResponse(content=b"[1, 2]"))
27
+
28
+ assert response.raw.read() == b""
29
+ assert list(response.iter_content(4)) == [b"[1, ", b"2]"]
30
+ assert list(response.iter_content(4)) == [b"[1, ", b"2]"]
31
+ assert list(response.iter_lines()) == [b"[1, 2]"]
32
+
33
+
34
+ def test_make_response_content_survives_closing() -> None:
35
+ """Test that the content can be read after the response is closed."""
36
+
37
+ expected = ExpectedResponse(content=b"null")
38
+
39
+ with make_response(make_request(), expected) as response:
40
+ pass
41
+
42
+ assert response.json() is None
43
+
44
+
45
+ def test_make_response_default() -> None:
46
+ """Test that `make_response` makes a 200 response with no body."""
47
+
48
+ response = make_response(make_request(), ExpectedResponse())
49
+
50
+ assert response.status_code == 200
51
+ assert response.reason == "OK"
52
+ assert response.ok
53
+ assert response.content == b""
54
+ assert response.headers == {}
55
+
56
+ response.raise_for_status()
57
+
58
+
59
+ @mark.parametrize(
60
+ ("status", "expect"),
61
+ [
62
+ (404, "404 Client Error: Not Found for url: https://example.com/"),
63
+ (500, "500 Server Error: Internal Server Error for url: https://example.com/"),
64
+ ],
65
+ )
66
+ def test_make_response_error_status(status: int, expect: str) -> None:
67
+ """Test that `make_response` makes a response that raises for an error status."""
68
+
69
+ response = make_response(make_request(), ExpectedResponse(status=status))
70
+
71
+ assert response.status_code == status
72
+ assert not response.ok
73
+
74
+ with raises(requests.HTTPError) as ex:
75
+ response.raise_for_status()
76
+
77
+ assert str(ex.value) == expect
78
+ assert ex.value.response is response
79
+
80
+
81
+ def test_make_response_describes_request() -> None:
82
+ """Test that `make_response` records the request and its URL."""
83
+
84
+ request = make_request(url="https://example.com/profile")
85
+
86
+ response = make_response(request, ExpectedResponse())
87
+
88
+ assert response.request is request
89
+ assert response.url == "https://example.com/profile"
90
+
91
+
92
+ def test_make_response_does_not_share_content() -> None:
93
+ """Test that responses made from the same expectation are read independently."""
94
+
95
+ expected = ExpectedResponse(content=b"null")
96
+
97
+ a = make_response(make_request(), expected)
98
+ b = make_response(make_request(), expected)
99
+
100
+ assert a.json() is None
101
+ assert b.json() is None
102
+
103
+
104
+ def test_make_response_unknown_status() -> None:
105
+ """Test that `make_response` gives a status it doesn't know an empty reason."""
106
+
107
+ response = make_response(make_request(), ExpectedResponse(status=299))
108
+
109
+ assert response.reason == ""
110
+ assert response.ok
@@ -1,12 +0,0 @@
1
- from dataclasses import dataclass
2
-
3
-
4
- @dataclass
5
- class Call:
6
- """A request call."""
7
-
8
- method: str
9
- """Upper-case HTTP method of the request's call."""
10
-
11
- url: str
12
- """URL of the request's call."""
@@ -1,82 +0,0 @@
1
- from urllib.parse import urlsplit
2
-
3
- from ..call import Call
4
- from ..request import prepare_request
5
- from ..rules import GlobalRules, HostRules
6
-
7
-
8
- class HostExpectations:
9
- """Expectations of requests to a specific host."""
10
-
11
- def __init__(
12
- self,
13
- name: str,
14
- rules: GlobalRules,
15
- ) -> None:
16
- """
17
- Initialise the host expectations.
18
-
19
- Args:
20
- name: Case-insensitive host name, like `example.com`.
21
- rules: Global rules to record this host's expectations in.
22
-
23
- Raises:
24
- requests.RequestException: `requests` couldn't prepare a URL for the host.
25
- ValueError: The name isn't only a host name.
26
- """
27
-
28
- url = prepare_request("GET", f"https://{name}/").url
29
-
30
- if urlsplit(str(url)).hostname != name.lower():
31
- raise ValueError(f"expected {name!r} to be only a host name")
32
-
33
- self._host_rules = rules.hosts.setdefault(name, HostRules())
34
- """Rules to record this host's own expectations in."""
35
-
36
- self._name = name
37
- """Host name."""
38
-
39
- self._rules = rules
40
- """Rules to record this host's expected calls in, in order with every host's."""
41
-
42
- def call(
43
- self,
44
- method: str,
45
- path: str,
46
- ) -> None:
47
- """
48
- Expect a request call to this host, over HTTPS.
49
-
50
- Args:
51
- method: HTTP method.
52
- path: Path on this host, starting with a slash, like `/users/me`.
53
-
54
- Raises:
55
- requests.RequestException: `requests` couldn't prepare the call's URL.
56
- ValueError: The path doesn't start with a slash.
57
- """
58
-
59
- if not path.startswith("/"):
60
- raise ValueError(f"expected path {path!r} to start with '/'")
61
-
62
- # Preparing normalises the method and URL just like a request's call is, so the
63
- # two can be compared.
64
- request = prepare_request(method, f"https://{self._name}{path}")
65
-
66
- call = Call(
67
- method=str(request.method),
68
- url=str(request.url),
69
- )
70
-
71
- self._rules.calls.append(call)
72
-
73
- def header(self, name: str, value: str) -> None:
74
- """
75
- Expect a header on every request to this host.
76
-
77
- Args:
78
- name: Case-insensitive header name.
79
- value: Header value.
80
- """
81
-
82
- self._host_rules.headers[name] = value
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes