|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import json
|
2 |
| -from collections.abc import AsyncIterator, Generator, Iterator |
| 4 | +import time |
| 5 | +from typing import TYPE_CHECKING |
3 | 6 |
|
4 |
| -import httpx |
5 | 7 | import pytest
|
6 |
| -import respx |
| 8 | +from werkzeug import Response |
7 | 9 |
|
8 | 10 | from apify_client._errors import ApifyApiError
|
9 | 11 | from apify_client._http_client import HTTPClient, HTTPClientAsync
|
10 | 12 |
|
11 |
| -_TEST_URL = 'http://example.com' |
| 13 | +if TYPE_CHECKING: |
| 14 | + from collections.abc import Iterator |
| 15 | + |
| 16 | + from pytest_httpserver import HTTPServer |
| 17 | + from werkzeug import Request |
| 18 | + |
| 19 | +_TEST_PATH = '/errors' |
12 | 20 | _EXPECTED_MESSAGE = 'some_message'
|
13 | 21 | _EXPECTED_TYPE = 'some_type'
|
14 | 22 | _EXPECTED_DATA = {
|
|
27 | 35 |
|
28 | 36 |
|
29 | 37 | @pytest.fixture
|
30 |
| -def mocked_response() -> Generator[respx.MockRouter]: |
31 |
| - response_content = json.dumps( |
32 |
| - {'error': {'message': _EXPECTED_MESSAGE, 'type': _EXPECTED_TYPE, 'data': _EXPECTED_DATA}} |
| 38 | +def test_endpoint(httpserver: HTTPServer) -> str: |
| 39 | + httpserver.expect_request(_TEST_PATH).respond_with_json( |
| 40 | + {'error': {'message': _EXPECTED_MESSAGE, 'type': _EXPECTED_TYPE, 'data': _EXPECTED_DATA}}, status=400 |
33 | 41 | )
|
34 |
| - with respx.mock() as respx_mock: |
35 |
| - respx_mock.get(_TEST_URL).mock(return_value=httpx.Response(400, content=response_content)) |
36 |
| - yield respx_mock |
| 42 | + return str(httpserver.url_for(_TEST_PATH)) |
| 43 | + |
| 44 | + |
| 45 | +def streaming_handler(_request: Request) -> Response: |
| 46 | + """Handler for streaming log requests.""" |
37 | 47 |
|
| 48 | + def generate_response() -> Iterator[bytes]: |
| 49 | + for i in range(len(RAW_ERROR)): |
| 50 | + yield RAW_ERROR[i : i + 1] |
| 51 | + time.sleep(0.01) |
38 | 52 |
|
39 |
| -@pytest.mark.usefixtures('mocked_response') |
40 |
| -def test_client_apify_api_error_with_data() -> None: |
| 53 | + return Response( |
| 54 | + response=(RAW_ERROR[i : i + 1] for i in range(len(RAW_ERROR))), |
| 55 | + status=403, |
| 56 | + mimetype='application/octet-stream', |
| 57 | + headers={'Content-Length': str(len(RAW_ERROR))}, |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def test_client_apify_api_error_with_data(test_endpoint: str) -> None: |
41 | 62 | """Test that client correctly throws ApifyApiError with error data from response."""
|
42 | 63 | client = HTTPClient()
|
43 | 64 |
|
44 | 65 | with pytest.raises(ApifyApiError) as e:
|
45 |
| - client.call(method='GET', url=_TEST_URL) |
| 66 | + client.call(method='GET', url=test_endpoint) |
46 | 67 |
|
47 | 68 | assert e.value.message == _EXPECTED_MESSAGE
|
48 | 69 | assert e.value.type == _EXPECTED_TYPE
|
49 | 70 | assert e.value.data == _EXPECTED_DATA
|
50 | 71 |
|
51 | 72 |
|
52 |
| -@pytest.mark.usefixtures('mocked_response') |
53 |
| -async def test_async_client_apify_api_error_with_data() -> None: |
| 73 | +async def test_async_client_apify_api_error_with_data(test_endpoint: str) -> None: |
54 | 74 | """Test that async client correctly throws ApifyApiError with error data from response."""
|
55 | 75 | client = HTTPClientAsync()
|
56 | 76 |
|
57 | 77 | with pytest.raises(ApifyApiError) as e:
|
58 |
| - await client.call(method='GET', url=_TEST_URL) |
| 78 | + await client.call(method='GET', url=test_endpoint) |
59 | 79 |
|
60 | 80 | assert e.value.message == _EXPECTED_MESSAGE
|
61 | 81 | assert e.value.type == _EXPECTED_TYPE
|
62 | 82 | assert e.value.data == _EXPECTED_DATA
|
63 | 83 |
|
64 | 84 |
|
65 |
| -def test_client_apify_api_error_streamed() -> None: |
| 85 | +def test_client_apify_api_error_streamed(httpserver: HTTPServer) -> None: |
66 | 86 | """Test that client correctly throws ApifyApiError when the response has stream."""
|
67 | 87 |
|
68 | 88 | error = json.loads(RAW_ERROR.decode())
|
69 | 89 |
|
70 |
| - class ByteStream(httpx._types.SyncByteStream): |
71 |
| - def __iter__(self) -> Iterator[bytes]: |
72 |
| - yield RAW_ERROR |
73 |
| - |
74 |
| - def close(self) -> None: |
75 |
| - pass |
76 |
| - |
77 |
| - stream_url = 'http://some-stream-url.com' |
78 |
| - |
79 | 90 | client = HTTPClient()
|
80 | 91 |
|
81 |
| - with respx.mock() as respx_mock: |
82 |
| - respx_mock.get(url=stream_url).mock(return_value=httpx.Response(stream=ByteStream(), status_code=403)) |
83 |
| - with pytest.raises(ApifyApiError) as e: |
84 |
| - client.call(method='GET', url=stream_url, stream=True, parse_response=False) |
| 92 | + httpserver.expect_request('/stream_error').respond_with_handler(streaming_handler) |
| 93 | + |
| 94 | + with pytest.raises(ApifyApiError) as e: |
| 95 | + client.call(method='GET', url=httpserver.url_for('/stream_error'), stream=True, parse_response=False) |
85 | 96 |
|
86 | 97 | assert e.value.message == error['error']['message']
|
87 | 98 | assert e.value.type == error['error']['type']
|
88 | 99 |
|
89 | 100 |
|
90 |
| -async def test_async_client_apify_api_error_streamed() -> None: |
| 101 | +async def test_async_client_apify_api_error_streamed(httpserver: HTTPServer) -> None: |
91 | 102 | """Test that async client correctly throws ApifyApiError when the response has stream."""
|
92 | 103 |
|
93 | 104 | error = json.loads(RAW_ERROR.decode())
|
94 | 105 |
|
95 |
| - class AsyncByteStream(httpx._types.AsyncByteStream): |
96 |
| - async def __aiter__(self) -> AsyncIterator[bytes]: |
97 |
| - yield RAW_ERROR |
98 |
| - |
99 |
| - async def aclose(self) -> None: |
100 |
| - pass |
101 |
| - |
102 |
| - stream_url = 'http://some-stream-url.com' |
103 |
| - |
104 | 106 | client = HTTPClientAsync()
|
105 | 107 |
|
106 |
| - with respx.mock() as respx_mock: |
107 |
| - respx_mock.get(url=stream_url).mock(return_value=httpx.Response(stream=AsyncByteStream(), status_code=403)) |
108 |
| - with pytest.raises(ApifyApiError) as e: |
109 |
| - await client.call(method='GET', url=stream_url, stream=True, parse_response=False) |
| 108 | + httpserver.expect_request('/stream_error').respond_with_handler(streaming_handler) |
| 109 | + |
| 110 | + with pytest.raises(ApifyApiError) as e: |
| 111 | + await client.call(method='GET', url=httpserver.url_for('/stream_error'), stream=True, parse_response=False) |
110 | 112 |
|
111 | 113 | assert e.value.message == error['error']['message']
|
112 | 114 | assert e.value.type == error['error']['type']
|
0 commit comments