File: test_requests.py

package info (click to toggle)
python-web-poet 0.23.2-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 908 kB
  • sloc: python: 6,112; makefile: 19
file content (301 lines) | stat: -rw-r--r-- 10,241 bytes parent folder | download | duplicates (3)
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
from __future__ import annotations

from typing import TYPE_CHECKING
from unittest import mock

import pytest

from web_poet.exceptions import HttpResponseError, RequestDownloaderVarError
from web_poet.page_inputs import (
    HttpClient,
    HttpRequest,
    HttpRequestBody,
    HttpRequestHeaders,
    HttpResponse,
)
from web_poet.requests import request_downloader_var

if TYPE_CHECKING:
    from collections.abc import Callable


@pytest.fixture
def async_mock():
    """Workaround since python 3.7 doesn't ship with asyncmock."""

    async def async_test(req):
        return HttpResponse(str(req.url), body=b"")

    mock.MagicMock.__await__ = lambda x: async_test(x).__await__()

    return async_test


@pytest.mark.asyncio
async def test_perform_request_from_httpclient(async_mock) -> None:
    url = "http://example.com"
    client = HttpClient()

    with pytest.raises(RequestDownloaderVarError):
        await client.get(url)

    request_downloader_var.set(async_mock)
    response = await client.get(url)

    # The async downloader implementation should return the HttpResponse
    assert str(response.url) == str(url)
    assert isinstance(response, HttpResponse)


@pytest.mark.asyncio
async def test_http_client_single_requests(async_mock) -> None:
    client = HttpClient(async_mock)

    with mock.patch("web_poet.page_inputs.client.HttpRequest") as mock_request:
        await client.request("url")
        await client.get("url-get", headers={"X-Headers": "123"})
        await client.post("url-post", headers={"X-Headers": "123"}, body=b"body value")
        assert mock_request.call_args_list == [
            mock.call(
                url="url",
                method="GET",
                headers=HttpRequestHeaders(),
                body=HttpRequestBody(),
            ),
            mock.call(
                url="url-get",
                method="GET",
                headers=HttpRequestHeaders({"X-Headers": "123"}),
                body=HttpRequestBody(),
            ),
            mock.call(
                url="url-post",
                method="POST",
                headers=HttpRequestHeaders({"X-Headers": "123"}),
                body=HttpRequestBody(b"body value"),
            ),
        ]


@pytest.fixture
def client_with_status() -> Callable:
    def _param_wrapper(status_code: int):
        async def stub_request_downloader(*args, **kwargs):
            async def stub(req):
                return HttpResponse(req.url, body=b"", status=status_code)

            return await stub(*args, **kwargs)

        return stub_request_downloader

    return _param_wrapper


@pytest.mark.asyncio
@pytest.mark.parametrize("method_name", ["request", "get", "post", "execute"])
async def test_http_client_allow_status(
    async_mock, client_with_status, method_name
) -> None:
    client = HttpClient(async_mock)

    # Simulate 500 Internal Server Error responses
    client._request_downloader = client_with_status(500)

    method = getattr(client, method_name)

    url_or_request: str | HttpRequest = "url"
    if method_name == "execute":
        # NOTE: We're ignoring the type below due to the following mypy bugs:
        #   - https://github.com/python/mypy/issues/10187
        #   - https://github.com/python/mypy/issues/5313
        #   - https://github.com/python-attrs/attrs/issues/889
        # Currently, the said bugs causes mypy to raise the following error:
        #   'Incompatible types in assignment (expression has type "ResponseUrl",
        #   variable has type "Optional[str]")'
        url_or_request = HttpRequest(url_or_request)  # type: ignore[arg-type]

    # Should handle single and multiple values
    await method(url_or_request, allow_status=500)
    response = await method(url_or_request, allow_status=[500, 503])
    assert isinstance(response, HttpResponse)
    assert response.status == 500

    # As well as strings
    await method(url_or_request, allow_status="500")
    await method(url_or_request, allow_status=["500", "503"])

    with pytest.raises(HttpResponseError) as excinfo:
        await method(url_or_request)
    assert isinstance(excinfo.value.request, HttpRequest)
    assert isinstance(excinfo.value.response, HttpResponse)
    assert str(excinfo.value).startswith("500 INTERNAL_SERVER_ERROR response for")

    with pytest.raises(HttpResponseError):
        await method(url_or_request, allow_status=406)
    assert isinstance(excinfo.value.request, HttpRequest)
    assert isinstance(excinfo.value.response, HttpResponse)
    assert str(excinfo.value).startswith("500 INTERNAL_SERVER_ERROR response for")

    # As long as "*" is present, then no errors would be raised
    await method(url_or_request, allow_status="*")
    await method(url_or_request, allow_status=[500, "*"])

    # Globbing isn't supported
    with pytest.raises(HttpResponseError):
        await method(url_or_request, allow_status="5*")
    assert isinstance(excinfo.value.request, HttpRequest)
    assert isinstance(excinfo.value.response, HttpResponse)
    assert str(excinfo.value).startswith("500 INTERNAL_SERVER_ERROR response for")


@pytest.mark.asyncio
async def test_http_client_keyword_enforcing(async_mock) -> None:
    """Only keyword args are allowed after the url param."""

    client = HttpClient(async_mock)

    with pytest.raises(TypeError):
        await client.request("url", "PATCH")  # type: ignore[misc]

    with pytest.raises(TypeError):
        await client.get("url", {"Content-Encoding": "utf-8"})  # type: ignore[misc]

    with pytest.raises(TypeError):
        await client.post("url", {"X-Header": "value"}, b"body")  # type: ignore[misc]


@pytest.mark.asyncio
async def test_http_client_execute(async_mock) -> None:
    client = HttpClient(async_mock)

    request = HttpRequest("url-1")
    response = await client.execute(request)

    assert isinstance(response, HttpResponse)
    assert str(response.url) == "url-1"


@pytest.mark.asyncio
async def test_http_client_batch_execute(async_mock) -> None:
    client = HttpClient(async_mock)

    requests = [
        HttpRequest("url-1"),
        HttpRequest("url-get", method="GET"),
        HttpRequest("url-post", method="POST"),
    ]
    responses = await client.batch_execute(*requests)

    assert all(isinstance(response, HttpResponse) for response in responses)


@pytest.fixture
def client_that_errs(async_mock) -> HttpClient:
    client = HttpClient(async_mock)

    # Simulate errors inside the request coroutines
    async def stub_request_downloader(*args, **kwargs):
        async def err():
            raise ValueError("test exception")

        return await err()

    client._request_downloader = stub_request_downloader

    return client


@pytest.mark.asyncio
async def test_http_client_batch_execute_with_exception(client_that_errs) -> None:
    requests = [
        HttpRequest("url-1"),
        HttpRequest("url-get", method="GET"),
        HttpRequest("url-post", method="POST"),
    ]
    responses = await client_that_errs.batch_execute(*requests, return_exceptions=True)

    assert len(responses) == 3
    assert isinstance(responses[0], Exception)
    assert isinstance(responses[1], Exception)
    assert isinstance(responses[2], Exception)


@pytest.mark.asyncio
async def test_http_client_batch_execute_with_exception_raised(
    client_that_errs,
) -> None:
    requests = [
        HttpRequest("url-1"),
    ]
    with pytest.raises(ValueError, match="test exception"):
        await client_that_errs.batch_execute(*requests)


@pytest.mark.asyncio
async def test_http_client_batch_execute_allow_status(
    async_mock, client_with_status
) -> None:
    client = HttpClient(async_mock)

    # Simulate 400 Bad Request
    client._request_downloader = client_with_status(400)

    requests = [HttpRequest("url-1"), HttpRequest("url-2"), HttpRequest("url-3")]

    await client.batch_execute(*requests, allow_status=400)
    await client.batch_execute(*requests, allow_status=[400, 403])
    await client.batch_execute(*requests, allow_status="400")
    responses = await client.batch_execute(*requests, allow_status=["400", "403"])

    for r in responses:
        assert isinstance(r, HttpResponse)
        assert r.status == 400

    with pytest.raises(HttpResponseError) as excinfo:
        await client.batch_execute(*requests)
    assert isinstance(excinfo.value.request, HttpRequest)
    assert isinstance(excinfo.value.response, HttpResponse)
    assert str(excinfo.value).startswith("400 BAD_REQUEST response for")

    with pytest.raises(HttpResponseError) as excinfo:
        await client.batch_execute(*requests, allow_status=406)
    assert isinstance(excinfo.value.request, HttpRequest)
    assert isinstance(excinfo.value.response, HttpResponse)
    assert str(excinfo.value).startswith("400 BAD_REQUEST response for")

    await client.batch_execute(*requests, return_exceptions=True, allow_status=400)
    await client.batch_execute(
        *requests, return_exceptions=True, allow_status=[400, 403]
    )
    await client.batch_execute(*requests, return_exceptions=True, allow_status="400")
    await client.batch_execute(
        *requests, return_exceptions=True, allow_status=["400", "403"]
    )

    responses = await client.batch_execute(*requests, return_exceptions=True)
    for r in responses:
        assert isinstance(r, HttpResponseError)
        assert isinstance(r.request, HttpRequest)
        assert isinstance(r.response, HttpResponse)
    assert all(str(r).startswith("400 BAD_REQUEST response for") for r in responses)

    responses = await client.batch_execute(
        *requests, return_exceptions=True, allow_status=408
    )
    for r in responses:
        assert isinstance(r, HttpResponseError)
        assert isinstance(r.request, HttpRequest)
        assert isinstance(r.response, HttpResponse)
    assert all(str(r).startswith("400 BAD_REQUEST response for") for r in responses)

    # These have no assertions since they're used to see if mypy raises an
    # error against them.
    for r in responses:
        if isinstance(r, HttpResponseError):
            r.request
            r.response
        else:
            r.url
            r.body
            r.status
            r.headers