Skip to content

Commit c8b3628

Browse files
committed
test: Run unit and integration tests across all built-in HTTP transports
1 parent 4ec385c commit c8b3628

21 files changed

Lines changed: 75 additions & 75 deletions

‎tests/_utils.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
if TYPE_CHECKING:
1515
from collections.abc import Awaitable, Callable
1616

17+
from apify_client.http_clients import HttpClient, HttpClientAsync
18+
1719
# Environment variable names for test configuration
1820
TOKEN_ENV_VAR = 'APIFY_TEST_USER_API_TOKEN'
1921
TOKEN_ENV_VAR_2 = 'APIFY_TEST_USER_2_API_TOKEN'
@@ -55,6 +57,14 @@ class KvsFixture(StorageFixture):
5557
keys_signature: dict[str, str]
5658

5759

60+
@dataclass(frozen=True)
61+
class HttpClientClasses:
62+
"""Synchronous and asynchronous variants of a built-in HTTP client."""
63+
64+
sync: type[HttpClient]
65+
async_: type[HttpClientAsync]
66+
67+
5868
def get_crypto_random_object_id(length: int = 17) -> str:
5969
"""Generate a cryptographically secure random object ID."""
6070
chars = 'abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789'

‎tests/integration/conftest.py‎

Lines changed: 11 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import json
44
import os
5-
from dataclasses import dataclass
65
from typing import TYPE_CHECKING
76

87
import pytest
@@ -12,15 +11,14 @@
1211
TOKEN_ENV_VAR,
1312
TOKEN_ENV_VAR_2,
1413
DatasetFixture,
14+
HttpClientClasses,
1515
KvsFixture,
1616
get_crypto_random_object_id,
1717
)
1818
from apify_client import ApifyClient, ApifyClientAsync
1919
from apify_client._consts import DEFAULT_API_URL
2020
from apify_client._utils.crypto import create_hmac_signature, create_storage_content_signature
2121
from apify_client.http_clients import (
22-
HttpClient,
23-
HttpClientAsync,
2422
HttpxHttpClient,
2523
HttpxHttpClientAsync,
2624
ImpitHttpClient,
@@ -31,24 +29,6 @@
3129
from collections.abc import AsyncGenerator, Generator
3230

3331

34-
@dataclass(frozen=True)
35-
class HttpClientClasses:
36-
"""Synchronous and asynchronous variants of a built-in HTTP client."""
37-
38-
sync: type[HttpClient]
39-
async_: type[HttpClientAsync]
40-
41-
42-
DEFAULT_HTTP_CLIENT_CLASSES = HttpClientClasses(sync=ImpitHttpClient, async_=ImpitHttpClientAsync)
43-
"""HTTP clients the live-API suite runs with unless a test asks for another transport."""
44-
45-
ALL_HTTP_CLIENT_CLASSES = [
46-
pytest.param(DEFAULT_HTTP_CLIENT_CLASSES, id='impit'),
47-
pytest.param(HttpClientClasses(sync=HttpxHttpClient, async_=HttpxHttpClientAsync), id='httpx'),
48-
]
49-
"""Every built-in HTTP client, for tests that exercise transport behavior rather than an API resource."""
50-
51-
5232
@pytest.fixture(scope='session')
5333
def api_token() -> str:
5434
"""Primary test user API token."""
@@ -126,18 +106,17 @@ def test_kvs_of_another_user(api_token_2: str) -> Generator[KvsFixture]:
126106
kvs_client.delete()
127107

128108

129-
@pytest.fixture
109+
@pytest.fixture(
110+
params=[
111+
pytest.param(HttpClientClasses(sync=ImpitHttpClient, async_=ImpitHttpClientAsync), id='impit'),
112+
pytest.param(HttpClientClasses(sync=HttpxHttpClient, async_=HttpxHttpClientAsync), id='httpx'),
113+
]
114+
)
130115
def http_client_classes(request: pytest.FixtureRequest) -> HttpClientClasses:
131-
"""Return the sync and async classes of the HTTP client the test runs with.
132-
133-
Defaults to Impit so the live-API suite isn't multiplied by every transport. A transport-level test opts into
134-
the full matrix with `@pytest.mark.parametrize('http_client_classes', ALL_HTTP_CLIENT_CLASSES, indirect=True)`.
135-
"""
136-
if not hasattr(request, 'param'):
137-
return DEFAULT_HTTP_CLIENT_CLASSES
138-
139-
assert isinstance(request.param, HttpClientClasses)
140-
return request.param
116+
"""Return the sync and async classes of the HTTP client the test runs with, once per built-in transport."""
117+
classes = request.param
118+
assert isinstance(classes, HttpClientClasses)
119+
return classes
141120

142121

143122
@pytest.fixture(params=['sync', 'async'])

‎tests/integration/test_apify_client.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,13 @@
44

55
from typing import TYPE_CHECKING
66

7-
import pytest
8-
97
from .._utils import maybe_await
10-
from .conftest import ALL_HTTP_CLIENT_CLASSES
118
from apify_client._models import UserPrivateInfo, UserPublicInfo
129

1310
if TYPE_CHECKING:
1411
from apify_client import ApifyClient, ApifyClientAsync
1512

1613

17-
@pytest.mark.parametrize('http_client_classes', ALL_HTTP_CLIENT_CLASSES, indirect=True)
1814
async def test_apify_client(client: ApifyClient | ApifyClientAsync) -> None:
1915
"""Test basic apify client functionality."""
2016
user_client = client.user('me')

‎tests/integration/test_dataset.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
maybe_await,
1919
poll_until_condition,
2020
)
21-
from .conftest import ALL_HTTP_CLIENT_CLASSES
2221
from apify_client._models import Dataset, DatasetListItem, DatasetStatistics, ListOfDatasets
2322
from apify_client._resource_clients.dataset import DatasetItemsPage
2423
from apify_client.errors import ApifyApiError
@@ -699,7 +698,6 @@ async def get_items() -> DatasetItemsPage:
699698
await maybe_await(dataset_client.delete())
700699

701700

702-
@pytest.mark.parametrize('http_client_classes', ALL_HTTP_CLIENT_CLASSES, indirect=True)
703701
async def test_dataset_stream_items(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None:
704702
"""Test streaming dataset items."""
705703
dataset_name = get_random_resource_name('dataset')

‎tests/integration/test_key_value_store.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
maybe_sleep,
2020
poll_until_condition,
2121
)
22-
from .conftest import ALL_HTTP_CLIENT_CLASSES
2322
from apify_client._models import KeyValueStore, KeyValueStoreKey, ListOfKeys, ListOfKeyValueStores
2423
from apify_client.errors import ApifyApiError
2524
from apify_client.http_clients import HttpResponse
@@ -707,7 +706,6 @@ async def get_keys() -> ListOfKeys:
707706
await maybe_await(store_client.delete())
708707

709708

710-
@pytest.mark.parametrize('http_client_classes', ALL_HTTP_CLIENT_CLASSES, indirect=True)
711709
async def test_key_value_store_stream_record_own(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None:
712710
"""Test streaming a record from one's own key-value store (no signature)."""
713711
store_name = get_random_resource_name('kvs')

‎tests/integration/test_log.py‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@
55
from contextlib import AbstractAsyncContextManager, AbstractContextManager
66
from typing import TYPE_CHECKING
77

8-
import pytest
9-
108
from .._utils import maybe_await
11-
from .conftest import ALL_HTTP_CLIENT_CLASSES
129
from apify_client._models import ListOfBuilds, Run
1310
from apify_client.http_clients import HttpResponse
1411

@@ -75,7 +72,6 @@ async def test_log_get_as_bytes(client: ApifyClient | ApifyClientAsync) -> None:
7572
await maybe_await(run_client.delete())
7673

7774

78-
@pytest.mark.parametrize('http_client_classes', ALL_HTTP_CLIENT_CLASSES, indirect=True)
7975
async def test_log_stream_from_run(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None:
8076
"""Test streaming a run's log via the stream() context manager."""
8177
actor = client.actor(HELLO_WORLD_ACTOR)

‎tests/unit/conftest.py‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import pytest
77
from pytest_httpserver import HTTPServer
88

9+
from .._utils import HttpClientClasses
910
from apify_client import ApifyClient, ApifyClientAsync
1011
from apify_client.http_clients import (
1112
HttpClient,
@@ -52,21 +53,31 @@ def async_client(httpserver: HTTPServer) -> ApifyClientAsync:
5253

5354
@pytest.fixture(
5455
params=[
55-
pytest.param(ImpitHttpClient, id='impit'),
56-
pytest.param(HttpxHttpClient, id='httpx'),
56+
pytest.param(HttpClientClasses(sync=ImpitHttpClient, async_=ImpitHttpClientAsync), id='impit'),
57+
pytest.param(HttpClientClasses(sync=HttpxHttpClient, async_=HttpxHttpClientAsync), id='httpx'),
5758
]
5859
)
59-
def http_client_class(request: pytest.FixtureRequest) -> type[HttpClient]:
60+
def http_client_classes(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> HttpClientClasses:
61+
"""Run the test once per built-in HTTP transport, making each the default the Apify clients construct.
62+
63+
A module opts every test it holds into the transport matrix with
64+
`pytestmark = pytest.mark.usefixtures('http_client_classes')`. Tests constructing transports directly get the
65+
same single parametrization axis through the derived `http_client_class` / `http_client_async_class` fixtures.
66+
"""
67+
classes = request.param
68+
assert isinstance(classes, HttpClientClasses)
69+
monkeypatch.setattr('apify_client._apify_client.ImpitHttpClient', classes.sync)
70+
monkeypatch.setattr('apify_client._apify_client.ImpitHttpClientAsync', classes.async_)
71+
return classes
72+
73+
74+
@pytest.fixture
75+
def http_client_class(http_client_classes: HttpClientClasses) -> type[HttpClient]:
6076
"""Return each built-in synchronous HTTP client class."""
61-
return request.param
77+
return http_client_classes.sync
6278

6379

64-
@pytest.fixture(
65-
params=[
66-
pytest.param(ImpitHttpClientAsync, id='impit'),
67-
pytest.param(HttpxHttpClientAsync, id='httpx'),
68-
]
69-
)
70-
def http_client_async_class(request: pytest.FixtureRequest) -> type[HttpClientAsync]:
80+
@pytest.fixture
81+
def http_client_async_class(http_client_classes: HttpClientClasses) -> type[HttpClientAsync]:
7182
"""Return each built-in asynchronous HTTP client class."""
72-
return request.param
83+
return http_client_classes.async_

‎tests/unit/test_actor_start_params.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
if TYPE_CHECKING:
1313
from pytest_httpserver import HTTPServer
1414

15+
pytestmark = pytest.mark.usefixtures('http_client_classes')
16+
1517
_MOCKED_ACTOR_ID = 'test_actor_id'
1618
_MOCKED_RUN_ID = 'test_run_id'
1719

‎tests/unit/test_client_errors.py‎

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import pytest
88
from werkzeug import Response
99

10-
from apify_client import ApifyClient, ApifyClientAsync
1110
from apify_client.errors import (
1211
ApifyApiError,
1312
ConflictError,
@@ -25,8 +24,11 @@
2524
from pytest_httpserver import HTTPServer
2625
from werkzeug import Request
2726

27+
from apify_client import ApifyClient, ApifyClientAsync
2828
from apify_client.http_clients import HttpClient, HttpClientAsync
2929

30+
pytestmark = pytest.mark.usefixtures('http_client_classes')
31+
3032
_TEST_PATH = '/errors'
3133
_EXPECTED_MESSAGE = 'some_message'
3234
_EXPECTED_TYPE = 'some_type'
@@ -84,24 +86,6 @@ def streaming_handler(_request: Request) -> Response:
8486
)
8587

8688

87-
@pytest.fixture
88-
def sync_client(httpserver: HTTPServer, http_client_class: type[HttpClient]) -> ApifyClient:
89-
return ApifyClient.with_custom_http_client(
90-
token='test',
91-
api_url=httpserver.url_for('/').removesuffix('/'),
92-
http_client=http_client_class(),
93-
)
94-
95-
96-
@pytest.fixture
97-
def async_client(httpserver: HTTPServer, http_client_async_class: type[HttpClientAsync]) -> ApifyClientAsync:
98-
return ApifyClientAsync.with_custom_http_client(
99-
token='test',
100-
api_url=httpserver.url_for('/').removesuffix('/'),
101-
http_client=http_client_async_class(),
102-
)
103-
104-
10589
@pytest.fixture
10690
def test_endpoint(httpserver: HTTPServer) -> str:
10791
httpserver.expect_request(_TEST_PATH).respond_with_json(

‎tests/unit/test_client_pagination.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@
6262
from werkzeug import Request
6363

6464

65+
pytestmark = pytest.mark.usefixtures('http_client_classes')
66+
6567
CollectionClient: TypeAlias = (
6668
ActorCollectionClient
6769
| BuildCollectionClient

0 commit comments

Comments
 (0)