diff --git a/docs/02_concepts/08_pagination.mdx b/docs/02_concepts/08_pagination.mdx index 99b343df6..460e0fe40 100644 --- a/docs/02_concepts/08_pagination.mdx +++ b/docs/02_concepts/08_pagination.mdx @@ -16,6 +16,8 @@ import IterateItemsAsyncExample from '!!raw-loader!./code/08_iterate_items_async import IterateItemsSyncExample from '!!raw-loader!./code/08_iterate_items_sync.py'; import IterateCollectionAsyncExample from '!!raw-loader!./code/08_iterate_collection_async.py'; import IterateCollectionSyncExample from '!!raw-loader!./code/08_iterate_collection_sync.py'; +import StoreSearchAsyncExample from '!!raw-loader!./code/08_store_search_async.py'; +import StoreSearchSyncExample from '!!raw-loader!./code/08_store_search_sync.py'; Most methods named `list` or `list_something` in the Apify client return a page model — a [Pydantic](https://docs.pydantic.dev/latest/) model such as `ListOfActors` or `ListOfDatasets`. Unstructured dataset items use the `DatasetItemsPage` dataclass instead. All page models share a consistent interface for working with paginated data and expose the following fields: @@ -27,7 +29,7 @@ Most methods named `list` or `list_something` in the Apify client return a page On `DatasetItemsPage`, `count` reports how many dataset rows the API scanned for the page. Filters drop items from a page and `unwind` multiplies them, so a page can hold fewer or more items than `count`. -Some methods paginate differently. For example, `RequestQueueClient.list_requests` returns a cursor-based `ListOfRequests` without the `total`, `offset`, and `count` fields. To fetch the next page, pass its `next_cursor` value back as the `cursor` parameter. Other examples include `list_keys` and `list_head`. Regardless, the primary results are always stored under the `items` field, and the `limit` field can be used to control the number of results returned. +Some methods paginate differently. For example, `RequestQueueClient.list_requests` returns a cursor-based `ListOfRequests` without the `total`, `offset`, and `count` fields. To fetch the next page, pass its `next_cursor` value back as the `cursor` parameter. Other examples include `list_keys` and `list_head`. `StoreCollectionClient.search` doesn't paginate at all. For details, see [Search Apify Store](#search-apify-store). Regardless, the primary results are always stored under the `items` field, and the `limit` field can be used to control the number of results returned. The following example shows how to fetch all items from a dataset using pagination: @@ -89,3 +91,29 @@ The next example uses `iterate_items` on a dataset client to stream items past a To read the items of a run that's still going, use `RunClient.iterate_dataset_items`. Its `offset` and `limit` also count dataset rows. For details, see [Retrieve Actor data](/api/client/python/docs/guides/retrieve-actor-data#read-items-while-the-run-is-going). + +## Search Apify Store + +`StoreCollectionClient.list` and `StoreCollectionClient.iterate` go through all Actors in [Apify Store](https://apify.com/store), page by page, in Store order. To find Actors by a text query, use `StoreCollectionClient.search` instead. + +A search isn't paginated. The API returns the Actors that match the query best as a single page of at most 100 Actors, ordered by relevance. There is no next page and no `offset`, and the API doesn't report how many Actors match in total. The method therefore returns a `StoreSearchResult` with two fields: + +- `items` - The matching Actors, best match first. +- `limit` - The limit the API applied. It's the `limit` you passed, or 100 if you passed more or none. + +When `items` holds as many Actors as `limit`, more Actors may match than were returned. To narrow the result, use a more specific query or the `category`, `username`, and `pricing_model` filters. + + + + + {StoreSearchAsyncExample} + + + + + {StoreSearchSyncExample} + + + + +The `search` and `sort_by` arguments of `list` and `iterate` are deprecated and will be removed in v4. The API ignores `sort_by`, and `search` moved to the `search` method. diff --git a/docs/02_concepts/code/08_store_search_async.py b/docs/02_concepts/code/08_store_search_async.py new file mode 100644 index 000000000..538544f84 --- /dev/null +++ b/docs/02_concepts/code/08_store_search_async.py @@ -0,0 +1,17 @@ +from apify_client import ApifyClientAsync + +TOKEN = 'MY-APIFY-TOKEN' + + +async def main() -> None: + apify_client = ApifyClientAsync(TOKEN) + + # Search returns the best matches as a single page of at most 100 Actors. + result = await apify_client.store().search('instagram posts', limit=10) + + for actor in result.items: + print(f'{actor.username}/{actor.name}') + + # With as many Actors as the applied limit, more Actors may match the query. + if len(result.items) == result.limit: + print('The result may be cut off. Narrow the search with a filter.') diff --git a/docs/02_concepts/code/08_store_search_sync.py b/docs/02_concepts/code/08_store_search_sync.py new file mode 100644 index 000000000..a756e3004 --- /dev/null +++ b/docs/02_concepts/code/08_store_search_sync.py @@ -0,0 +1,21 @@ +from apify_client import ApifyClient + +TOKEN = 'MY-APIFY-TOKEN' + + +def main() -> None: + apify_client = ApifyClient(TOKEN) + + # Search returns the best matches as a single page of at most 100 Actors. + result = apify_client.store().search('instagram posts', limit=10) + + for actor in result.items: + print(f'{actor.username}/{actor.name}') + + # With as many Actors as the applied limit, more Actors may match the query. + if len(result.items) == result.limit: + print('The result may be cut off. Narrow the search with a filter.') + + +if __name__ == '__main__': + main() diff --git a/src/apify_client/_apify_client.py b/src/apify_client/_apify_client.py index 5936aa945..c7b930da7 100644 --- a/src/apify_client/_apify_client.py +++ b/src/apify_client/_apify_client.py @@ -464,7 +464,7 @@ def user(self, user_id: str | None = None) -> UserClient: return UserClient(resource_id=user_id, **self._base_kwargs) def store(self) -> StoreCollectionClient: - """Get the sub-client for the Apify Store, allowing to list Actors published in the store.""" + """Get the sub-client for the Apify Store, allowing to list and search Actors published in the Store.""" return StoreCollectionClient(**self._base_kwargs) @@ -854,5 +854,5 @@ def user(self, user_id: str | None = None) -> UserClientAsync: return UserClientAsync(resource_id=user_id, **self._base_kwargs) def store(self) -> StoreCollectionClientAsync: - """Get the sub-client for the Apify Store, allowing to list Actors published in the store.""" + """Get the sub-client for the Apify Store, allowing to list and search Actors published in the Store.""" return StoreCollectionClientAsync(**self._base_kwargs) diff --git a/src/apify_client/_resource_clients/store_collection.py b/src/apify_client/_resource_clients/store_collection.py index 4a3462d4f..421b38bf6 100644 --- a/src/apify_client/_resource_clients/store_collection.py +++ b/src/apify_client/_resource_clients/store_collection.py @@ -1,26 +1,93 @@ from __future__ import annotations +import warnings +from dataclasses import dataclass from typing import TYPE_CHECKING, Any from apify_client._docs import docs_group -from apify_client._models import ListOfStoreActors, ListOfStoreActorsResponse +from apify_client._logging import _set_client_details +from apify_client._models import ListOfStoreActors, ListOfStoreActorsResponse, StoreActor from apify_client._pagination import get_items_iterator, get_items_iterator_async from apify_client._resource_clients._resource_client import ResourceClient, ResourceClientAsync from apify_client._utils.http import validate_response if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterator + from collections.abc import AsyncIterator, Awaitable, Callable, Iterator - from apify_client._models import StoreActor from apify_client.types import Timeout +@docs_group('Other') +@dataclass +class StoreSearchResult: + """The single page of Actors returned by the `search` method. + + The API answers an Apify Store search with one page of the best matches. It reports the number of Actors returned + as the total and zero as the offset, whatever the query matches, so this class has no `total`, `offset` or `count`. + """ + + items: list[StoreActor] + """The Actors matching the query, best match first.""" + + limit: int + """The maximum number of Actors the API allowed in this result. + + It is the requested `limit`, or the API's maximum when no limit or a larger one was requested. With as many + `items` as this, more Actors may match the query than were returned. + """ + + +def _warn_about_deprecated_arguments(*, search: str | None, sort_by: str | None) -> None: + """Emit a `DeprecationWarning` for each deprecated argument that is set, pointing at the caller of the method. + + An empty `search` is not a search, so it gets no warning: the API answers it with the Store listing, and the + `search` method rejects it. + """ + # The frames up to the caller are this helper, the public method and its `WithLogDetailsClient` wrapper. + stacklevel = 4 + if search: + warnings.warn( + 'The `search` argument is deprecated and will be removed in v4. Use the `search` method instead.', + DeprecationWarning, + stacklevel=stacklevel, + ) + if sort_by is not None: + warnings.warn( + 'The `sort_by` argument is deprecated and will be removed in v4. The API ignores it.', + DeprecationWarning, + stacklevel=stacklevel, + ) + + +def _validate_search_query(search: str) -> None: + """Reject an empty query, which the API answers with the Store listing. + + Raises: + ValueError: If `search` is empty. + """ + if not search: + raise ValueError('`search` must not be empty. To go through the Store without a query, use `list`.') + + +def _iterate_page(get_page: Callable[[], ListOfStoreActors]) -> Iterator[StoreActor]: + """Yield the Actors of the single page that `get_page` returns.""" + page = get_page() + yield from page.items + + +async def _iterate_page_async(get_page: Callable[[], Awaitable[ListOfStoreActors]]) -> AsyncIterator[StoreActor]: + """Yield the Actors of the single page that `get_page` returns.""" + page = await get_page() + for item in page.items: + yield item + + @docs_group('Resource clients') class StoreCollectionClient(ResourceClient): - """Sub-client for the Apify store collection. + """Sub-client for the Apify Store collection. - Provides methods to browse the Apify store, e.g. list available Actors. Obtain an instance via an appropriate - method on the `ApifyClient` class. + Provides methods to browse the Apify Store, e.g. list available Actors or search them. Obtain an instance via an + appropriate method on the `ApifyClient` class. """ def __init__( @@ -47,17 +114,17 @@ def list( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> ListOfStoreActors: - """List Actors in Apify store. + """List Actors in Apify Store, ordered by their position in the Store. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the API returns the best matches as a + single page of at most 100 Actors, ignores `offset`, and reports the number of Actors returned as + `total`. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -69,18 +136,18 @@ def list( Returns: The list of available Actors matching the specified filters. """ - result = self._list( - timeout=timeout, + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) + return self._list_actors( limit=limit, offset=offset, search=search, - sortBy=sort_by, + sort_by=sort_by, category=category, username=username, - pricingModel=pricing_model, - includeUnrunnableActors=include_unrunnable_actors, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, ) - return validate_response(ListOfStoreActorsResponse, result).data def iterate( self, @@ -96,7 +163,7 @@ def iterate( chunk_size: int | None = None, timeout: Timeout = 'medium', ) -> Iterator[StoreActor]: - """Iterate over Actors in Apify store. + """Iterate over Actors in Apify Store, ordered by their position in the Store. Simple `list` does only one API call, possibly not listing all items matching the criteria. This method returns an iterator that is capable of making multiple API calls to retrieve all items matching the criteria. @@ -106,10 +173,10 @@ def iterate( Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the iterator makes a single API call and + yields the best matches, at most 100 Actors, as the API has no further page of a search. `offset` and + `chunk_size` have no effect then. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -120,11 +187,14 @@ def iterate( timeout: Timeout for the API HTTP request. Yields: - The Actors in the store matching the specified filters. + The Actors in the Store matching the specified filters. """ + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfStoreActors: - return self.list( + # Another client call between two pages overwrites the log context, so every page request sets it again. + _set_client_details(StoreCollectionClient.list, self) + return self._list_actors( limit=limit, offset=offset, search=search, @@ -136,15 +206,96 @@ def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfS timeout=timeout, ) + if search: + # The API ignores `offset` for a search, so asking for another page would return the same Actors again. + return _iterate_page(lambda: _callback(limit=limit, offset=offset)) + return get_items_iterator(_callback, limit=limit, offset=offset, chunk_size=chunk_size) + def search( + self, + search: str, + *, + limit: int | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout = 'medium', + ) -> StoreSearchResult: + """Search Apify Store and return the Actors that match the query best, ordered by relevance. + + The API answers a search with a single page of at most 100 Actors. There is no next page and no way to skip + results, and the API does not report how many Actors match the query in total. A result holding as many + Actors as its `limit` can therefore be cut off: narrow it down with a more specific query or with the + `category`, `username` and `pricing_model` filters. To go through the whole Store, use `list` or `iterate`. + + https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store + + Args: + search: Text to search for. It can't be empty. + limit: How many Actors to return. The API returns at most 100 Actors for a search, which is also the + default, and reduces a larger value to 100. + category: Filter by this category. + username: Filter by this username. + pricing_model: Filter by this pricing model. + include_unrunnable_actors: Whether to include Actors that are not safe to run automatically, such as + Actors whose developers have not passed KYC, or full-permission Actors without a large user base. + By default, they are excluded. + timeout: Timeout for the API HTTP request. + + Returns: + The matching Actors, best match first, and the limit the API applied. + + Raises: + ValueError: If `search` is empty. + """ + _validate_search_query(search) + page = self._list_actors( + limit=limit, + search=search, + category=category, + username=username, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, + ) + return StoreSearchResult(items=page.items, limit=page.limit) + + def _list_actors( + self, + *, + limit: int | None = None, + offset: int | None = None, + search: str | None = None, + sort_by: str | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout, + ) -> ListOfStoreActors: + """Request one page of Store Actors, which the API fills by search when `search` is set.""" + result = self._list( + timeout=timeout, + limit=limit, + offset=offset, + search=search, + sortBy=sort_by, + category=category, + username=username, + pricingModel=pricing_model, + includeUnrunnableActors=include_unrunnable_actors, + ) + return validate_response(ListOfStoreActorsResponse, result).data + @docs_group('Resource clients') class StoreCollectionClientAsync(ResourceClientAsync): - """Sub-client for the Apify store collection. + """Sub-client for the Apify Store collection. - Provides methods to browse the Apify store, e.g. list available Actors. Obtain an instance via an appropriate - method on the `ApifyClientAsync` class. + Provides methods to browse the Apify Store, e.g. list available Actors or search them. Obtain an instance via an + appropriate method on the `ApifyClientAsync` class. """ def __init__( @@ -171,17 +322,17 @@ async def list( include_unrunnable_actors: bool | None = None, timeout: Timeout = 'medium', ) -> ListOfStoreActors: - """List Actors in Apify store. + """List Actors in Apify Store, ordered by their position in the Store. https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the API returns the best matches as a + single page of at most 100 Actors, ignores `offset`, and reports the number of Actors returned as + `total`. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -193,18 +344,18 @@ async def list( Returns: The list of available Actors matching the specified filters. """ - result = await self._list( - timeout=timeout, + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) + return await self._list_actors( limit=limit, offset=offset, search=search, - sortBy=sort_by, + sort_by=sort_by, category=category, username=username, - pricingModel=pricing_model, - includeUnrunnableActors=include_unrunnable_actors, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, ) - return validate_response(ListOfStoreActorsResponse, result).data def iterate( self, @@ -220,7 +371,7 @@ def iterate( chunk_size: int | None = None, timeout: Timeout = 'medium', ) -> AsyncIterator[StoreActor]: - """Iterate over Actors in Apify store. + """Iterate over Actors in Apify Store, ordered by their position in the Store. Simple `list` does only one API call, possibly not listing all items matching the criteria. This method returns an iterator that is capable of making multiple API calls to retrieve all items matching the criteria. @@ -230,10 +381,10 @@ def iterate( Args: limit: How many Actors to list. offset: What Actor to include as first when retrieving the list. - search: String to search by. The search runs on the following fields: title, name, description, username, - readme. - sort_by: Deprecated. The API ignores this argument. Results are ordered by relevance when `search` is used, - and by Store position otherwise. + search: Deprecated. Use the `search` method. With this argument, the iterator makes a single API call and + yields the best matches, at most 100 Actors, as the API has no further page of a search. `offset` and + `chunk_size` have no effect then. + sort_by: Deprecated. The API ignores this argument. category: Filter by this category. username: Filter by this username. pricing_model: Filter by this pricing model. @@ -244,11 +395,14 @@ def iterate( timeout: Timeout for the API HTTP request. Yields: - The Actors in the store matching the specified filters. + The Actors in the Store matching the specified filters. """ + _warn_about_deprecated_arguments(search=search, sort_by=sort_by) async def _callback(*, limit: int | None = None, offset: int | None = None) -> ListOfStoreActors: - return await self.list( + # Another client call between two pages overwrites the log context, so every page request sets it again. + _set_client_details(StoreCollectionClientAsync.list, self) + return await self._list_actors( limit=limit, offset=offset, search=search, @@ -260,4 +414,85 @@ async def _callback(*, limit: int | None = None, offset: int | None = None) -> L timeout=timeout, ) + if search: + # The API ignores `offset` for a search, so asking for another page would return the same Actors again. + return _iterate_page_async(lambda: _callback(limit=limit, offset=offset)) + return get_items_iterator_async(_callback, limit=limit, offset=offset, chunk_size=chunk_size) + + async def search( + self, + search: str, + *, + limit: int | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout = 'medium', + ) -> StoreSearchResult: + """Search Apify Store and return the Actors that match the query best, ordered by relevance. + + The API answers a search with a single page of at most 100 Actors. There is no next page and no way to skip + results, and the API does not report how many Actors match the query in total. A result holding as many + Actors as its `limit` can therefore be cut off: narrow it down with a more specific query or with the + `category`, `username` and `pricing_model` filters. To go through the whole Store, use `list` or `iterate`. + + https://docs.apify.com/api/v2/#/reference/store/store-actors-collection/get-list-of-actors-in-store + + Args: + search: Text to search for. It can't be empty. + limit: How many Actors to return. The API returns at most 100 Actors for a search, which is also the + default, and reduces a larger value to 100. + category: Filter by this category. + username: Filter by this username. + pricing_model: Filter by this pricing model. + include_unrunnable_actors: Whether to include Actors that are not safe to run automatically, such as + Actors whose developers have not passed KYC, or full-permission Actors without a large user base. + By default, they are excluded. + timeout: Timeout for the API HTTP request. + + Returns: + The matching Actors, best match first, and the limit the API applied. + + Raises: + ValueError: If `search` is empty. + """ + _validate_search_query(search) + page = await self._list_actors( + limit=limit, + search=search, + category=category, + username=username, + pricing_model=pricing_model, + include_unrunnable_actors=include_unrunnable_actors, + timeout=timeout, + ) + return StoreSearchResult(items=page.items, limit=page.limit) + + async def _list_actors( + self, + *, + limit: int | None = None, + offset: int | None = None, + search: str | None = None, + sort_by: str | None = None, + category: str | None = None, + username: str | None = None, + pricing_model: str | None = None, + include_unrunnable_actors: bool | None = None, + timeout: Timeout, + ) -> ListOfStoreActors: + """Request one page of Store Actors, which the API fills by search when `search` is set.""" + result = await self._list( + timeout=timeout, + limit=limit, + offset=offset, + search=search, + sortBy=sort_by, + category=category, + username=username, + pricingModel=pricing_model, + includeUnrunnableActors=include_unrunnable_actors, + ) + return validate_response(ListOfStoreActorsResponse, result).data diff --git a/tests/integration/test_store.py b/tests/integration/test_store.py index 696e5bab2..576cdf0ad 100644 --- a/tests/integration/test_store.py +++ b/tests/integration/test_store.py @@ -1,4 +1,4 @@ -"""Unified tests for store (sync + async).""" +"""Unified tests for Apify Store (sync + async).""" from __future__ import annotations @@ -9,29 +9,74 @@ from .._utils import maybe_await from apify_client._models import ListOfStoreActors, StoreActor +from apify_client._resource_clients.store_collection import StoreSearchResult if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync async def test_store_list(client: ApifyClient | ApifyClientAsync) -> None: - """Test listing public Actors in the store.""" + """Test listing public Actors in the Store.""" actors_list = await maybe_await(client.store().list(limit=10)) assert isinstance(actors_list, ListOfStoreActors) assert actors_list.items is not None - assert len(actors_list.items) > 0 # Store always has actors + assert len(actors_list.items) > 0 # Store always has Actors + + +async def test_store_search(client: ApifyClient | ApifyClientAsync) -> None: + """Test that a Store search returns the best matches as one page.""" + result = await maybe_await(client.store().search('web scraper', limit=5)) + assert isinstance(result, StoreSearchResult) + assert 0 < len(result.items) <= 5 + assert result.limit == 5 + for actor in result.items: + assert isinstance(actor, StoreActor) + + +async def test_store_search_returns_at_most_100_actors(client: ApifyClient | ApifyClientAsync) -> None: + """Test that a Store search returns at most 100 Actors, whatever limit it is asked for.""" + default_result = await maybe_await(client.store().search('scraper')) + large_result = await maybe_await(client.store().search('scraper', limit=1000)) + assert default_result.limit == 100 + assert 0 < len(default_result.items) <= 100 + assert large_result.limit == 100 + assert 0 < len(large_result.items) <= 100 + + +async def test_store_search_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: + """Test a Store search filtered by a known username (apify).""" + result = await maybe_await(client.store().search('scraper', limit=10, username='apify')) + assert len(result.items) > 0 + for actor in result.items: + assert actor.username == 'apify' -async def test_store_list_with_search(client: ApifyClient | ApifyClientAsync) -> None: - """Test listing store with search filter.""" - store_page = await maybe_await(client.store().list(limit=5, search='web scraper')) +async def test_store_list_with_deprecated_search(client: ApifyClient | ApifyClientAsync) -> None: + """Test that the Store listing still accepts the deprecated `search` and returns the search page.""" + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated'): + store_page = await maybe_await(client.store().list(limit=5, search='web scraper')) assert isinstance(store_page, ListOfStoreActors) - assert store_page.items is not None - assert isinstance(store_page.items, list) + assert 0 < len(store_page.items) <= 5 + + +async def test_store_iterate_with_deprecated_search(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: + """Test that iterating with the deprecated `search` ends after the single page the API has for a search.""" + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated'): + iterator = client.store().iterate(search='scraper') + if is_async: + assert isinstance(iterator, AsyncIterator) + collected = [actor async for actor in iterator] + else: + assert isinstance(iterator, Iterator) + collected = list(iterator) + + assert 0 < len(collected) <= 100 + actor_ids = {actor.id for actor in collected} + assert len(actor_ids) == len(collected) async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: - """Test store listing pagination.""" + """Test Store listing pagination.""" page1 = await maybe_await(client.store().list(limit=5, offset=0)) page2 = await maybe_await(client.store().list(limit=5, offset=5)) assert isinstance(page1, ListOfStoreActors) @@ -43,7 +88,7 @@ async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> @pytest.mark.parametrize('pricing_model', ['FREE', 'FLAT_PRICE_PER_MONTH', 'PRICE_PER_DATASET_ITEM', 'PAY_PER_EVENT']) async def test_store_list_filter_by_pricing_model(client: ApifyClient | ApifyClientAsync, pricing_model: str) -> None: - """Test listing store actors filtered by each supported pricing model. + """Test listing Store Actors filtered by each supported pricing model. This exercises both the filter parameter and the Pydantic models that parse the responses for each pricing variant. @@ -60,7 +105,7 @@ async def test_store_list_filter_by_pricing_model(client: ApifyClient | ApifyCli async def test_store_list_filter_by_username(client: ApifyClient | ApifyClientAsync) -> None: - """Test listing store actors filtered by a known username (apify).""" + """Test listing Store Actors filtered by a known username (apify).""" page = await maybe_await(client.store().list(limit=10, username='apify')) assert isinstance(page, ListOfStoreActors) assert len(page.items) > 0 @@ -69,17 +114,18 @@ async def test_store_list_filter_by_username(client: ApifyClient | ApifyClientAs async def test_store_list_accepts_sort_by(client: ApifyClient | ApifyClientAsync) -> None: - """Test that the store listing accepts the deprecated `sort_by`. + """Test that the Store listing accepts the deprecated `sort_by`. The API accepts `sortBy` for compatibility but ignores it, so the order is not asserted. """ - page = await maybe_await(client.store().list(limit=10, sort_by='popularity')) + with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated'): + page = await maybe_await(client.store().list(limit=10, sort_by='popularity')) assert isinstance(page, ListOfStoreActors) assert len(page.items) > 0 async def test_store_iterate(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: - """Test paginated iteration over store Actors.""" + """Test paginated iteration over Store Actors.""" iterator = client.store().iterate(limit=20) collected: list[StoreActor] = [] if is_async: diff --git a/tests/unit/test_store_collection_params.py b/tests/unit/test_store_collection_params.py index d660bcac7..b828217f4 100644 --- a/tests/unit/test_store_collection_params.py +++ b/tests/unit/test_store_collection_params.py @@ -1,11 +1,16 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING +import logging +import warnings +from typing import TYPE_CHECKING, Any import pytest from werkzeug import Request, Response +from apify_client._logging import logger_name +from apify_client._resource_clients.store_collection import StoreSearchResult + if TYPE_CHECKING: from collections.abc import Callable @@ -28,11 +33,35 @@ } } +_STORE_ACTORS = [ + { + 'id': f'actor-id-{index}', + 'title': f'Actor {index}', + 'name': f'actor-{index}', + 'username': 'jane', + 'stats': {'totalUsers': 1, 'actorReviewRating': 0, 'actorReviewCount': 0}, + } + for index in range(2) +] + +# A full page of two Actors, served for every request. The API answers a search this way: with the same page +# whatever `offset` it is sent, and with the number of Actors returned as `total`. +_FULL_PAGE_RESPONSE = { + 'data': { + 'total': 2, + 'offset': 0, + 'limit': 2, + 'desc': False, + 'count': 2, + 'items': _STORE_ACTORS, + } +} + -def capture(captured: list[Request]) -> Callable[[Request], Response]: +def capture(captured: list[Request], response: dict[str, Any] = _STORE_RESPONSE) -> Callable[[Request], Response]: def handler(request: Request) -> Response: captured.append(request) - return Response(json.dumps(_STORE_RESPONSE), status=200, mimetype='application/json') + return Response(json.dumps(response), status=200, mimetype='application/json') return handler @@ -84,3 +113,269 @@ async def test_iterate_sends_include_unrunnable_actors_async( assert actors == [] assert len(captured) == 1 assert captured[0].args.get('includeUnrunnableActors') == 'true' + + +def test_search_sends_query_and_filters(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`search` sends one request with the query, the limit and the filters, and no offset.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + + sync_client.store().search( + 'web scraper', + limit=2, + category='AI', + username='jane', + pricing_model='FREE', + include_unrunnable_actors=True, + ) + + assert len(captured) == 1 + assert captured[0].args.to_dict() == { + 'search': 'web scraper', + 'limit': '2', + 'category': 'AI', + 'username': 'jane', + 'pricingModel': 'FREE', + 'includeUnrunnableActors': 'true', + } + + +async def test_search_sends_query_and_filters_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: + """Async `search` sends one request with the query, the limit and the filters, and no offset.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + + await async_client.store().search( + 'web scraper', + limit=2, + category='AI', + username='jane', + pricing_model='FREE', + include_unrunnable_actors=True, + ) + + assert len(captured) == 1 + assert captured[0].args.to_dict() == { + 'search': 'web scraper', + 'limit': '2', + 'category': 'AI', + 'username': 'jane', + 'pricingModel': 'FREE', + 'includeUnrunnableActors': 'true', + } + + +def test_search_returns_items_and_applied_limit(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`search` returns the Actors and the limit the API applied.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) + + result = sync_client.store().search(search='web scraper') + + assert isinstance(result, StoreSearchResult) + assert [actor.id for actor in result.items] == ['actor-id-0', 'actor-id-1'] + assert result.limit == 2 + + +async def test_search_returns_items_and_applied_limit_async( + httpserver: HTTPServer, async_client: ApifyClientAsync +) -> None: + """Async `search` returns the Actors and the limit the API applied.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) + + result = await async_client.store().search(search='web scraper') + + assert isinstance(result, StoreSearchResult) + assert [actor.id for actor in result.items] == ['actor-id-0', 'actor-id-1'] + assert result.limit == 2 + + +def test_search_rejects_empty_query(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`search` raises for an empty query without sending a request.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.raises(ValueError, match='must not be empty'): + sync_client.store().search('') + + assert captured == [] + + +async def test_search_rejects_empty_query_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: + """Async `search` raises for an empty query without sending a request.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.raises(ValueError, match='must not be empty'): + await async_client.store().search('') + + assert captured == [] + + +@pytest.mark.parametrize( + ('search', 'sort_by', 'message'), + [ + pytest.param('web scraper', None, '`search` argument is deprecated', id='search'), + pytest.param(None, 'popularity', '`sort_by` argument is deprecated', id='sort_by'), + ], +) +def test_list_warns_about_deprecated_argument( + httpserver: HTTPServer, sync_client: ApifyClient, search: str | None, sort_by: str | None, message: str +) -> None: + """`list` warns about a deprecated argument at the caller's line and still sends it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.warns(DeprecationWarning, match=message) as record: + sync_client.store().list(search=search, sort_by=sort_by) + + assert [warning.filename for warning in record] == [__file__] + assert len(captured) == 1 + assert captured[0].args.get('search') == search + assert captured[0].args.get('sortBy') == sort_by + + +@pytest.mark.parametrize( + ('search', 'sort_by', 'message'), + [ + pytest.param('web scraper', None, '`search` argument is deprecated', id='search'), + pytest.param(None, 'popularity', '`sort_by` argument is deprecated', id='sort_by'), + ], +) +async def test_list_warns_about_deprecated_argument_async( + httpserver: HTTPServer, async_client: ApifyClientAsync, search: str | None, sort_by: str | None, message: str +) -> None: + """Async `list` warns about a deprecated argument at the caller's line and still sends it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured)) + + with pytest.warns(DeprecationWarning, match=message) as record: + await async_client.store().list(search=search, sort_by=sort_by) + + assert [warning.filename for warning in record] == [__file__] + assert len(captured) == 1 + assert captured[0].args.get('search') == search + assert captured[0].args.get('sortBy') == sort_by + + +def test_iterate_with_search_requests_a_single_page(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`iterate` with the deprecated `search` warns once and yields the single page the API has for a search.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + + # The limit leaves room for a second page, so an iterator that pages a search sends two requests. + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated') as record: + actors = list(sync_client.store().iterate(search='web scraper', limit=4)) + + assert [warning.filename for warning in record] == [__file__] + assert [actor.id for actor in actors] == ['actor-id-0', 'actor-id-1'] + assert len(captured) == 1 + + +async def test_iterate_with_search_requests_a_single_page_async( + httpserver: HTTPServer, async_client: ApifyClientAsync +) -> None: + """Async `iterate` with the deprecated `search` warns once and yields the single page the API has for a search.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + + # The limit leaves room for a second page, so an iterator that pages a search sends two requests. + with pytest.warns(DeprecationWarning, match='`search` argument is deprecated') as record: + actors = [actor async for actor in async_client.store().iterate(search='web scraper', limit=4)] + + assert [warning.filename for warning in record] == [__file__] + assert [actor.id for actor in actors] == ['actor-id-0', 'actor-id-1'] + assert len(captured) == 1 + + +def test_iterate_with_sort_by_warns_and_still_pages(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`iterate` warns about the deprecated `sort_by` at the caller's line and pages as it does without it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + + with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated') as record: + actors = list(sync_client.store().iterate(sort_by='popularity', limit=4)) + + assert [warning.filename for warning in record] == [__file__] + assert len(actors) == 4 + assert [request.args.get('offset') for request in captured] == ['0', '2'] + + +async def test_iterate_with_sort_by_warns_and_still_pages_async( + httpserver: HTTPServer, async_client: ApifyClientAsync +) -> None: + """Async `iterate` warns about the deprecated `sort_by` at the caller's line and pages as it does without it.""" + captured: list[Request] = [] + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_handler(capture(captured, _FULL_PAGE_RESPONSE)) + + with pytest.warns(DeprecationWarning, match='`sort_by` argument is deprecated') as record: + actors = [actor async for actor in async_client.store().iterate(sort_by='popularity', limit=4)] + + assert [warning.filename for warning in record] == [__file__] + assert len(actors) == 4 + assert [request.args.get('offset') for request in captured] == ['0', '2'] + + +def test_empty_search_is_not_deprecated(httpserver: HTTPServer, sync_client: ApifyClient) -> None: + """`list` and `iterate` don't warn about an empty `search`, which the API answers with the listing.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_STORE_RESPONSE) + + with warnings.catch_warnings(): + warnings.simplefilter('error', DeprecationWarning) + sync_client.store().list(search='') + actors = list(sync_client.store().iterate(search='')) + + assert actors == [] + + +async def test_empty_search_is_not_deprecated_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None: + """Async `list` and `iterate` don't warn about an empty `search`, which the API answers with the listing.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_STORE_RESPONSE) + + with warnings.catch_warnings(): + warnings.simplefilter('error', DeprecationWarning) + await async_client.store().list(search='') + actors = [actor async for actor in async_client.store().iterate(search='')] + + assert actors == [] + + +def test_iterate_page_requests_keep_their_log_context( + httpserver: HTTPServer, sync_client: ApifyClient, caplog: pytest.LogCaptureFixture +) -> None: + """`iterate` logs every page request as a Store listing, also after another client call between two pages.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) + iterator = sync_client.store().iterate(limit=4) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + next(iterator) + sync_client.store().search('web scraper') + list(iterator) + + requests = [record for record in caplog.records if record.getMessage() == 'Request successful'] + client_methods = [record.__dict__['client_method'] for record in requests] + assert client_methods == [ + 'StoreCollectionClient.list', + 'StoreCollectionClient.search', + 'StoreCollectionClient.list', + ] + + +async def test_iterate_page_requests_keep_their_log_context_async( + httpserver: HTTPServer, async_client: ApifyClientAsync, caplog: pytest.LogCaptureFixture +) -> None: + """Async `iterate` logs every page request as a Store listing, also after another client call between two pages.""" + httpserver.expect_request(_STORE_PATH, method='GET').respond_with_json(_FULL_PAGE_RESPONSE) + iterator = async_client.store().iterate(limit=4) + + with caplog.at_level(logging.DEBUG, logger=logger_name): + await anext(iterator) + await async_client.store().search('web scraper') + _ = [actor async for actor in iterator] + + requests = [record for record in caplog.records if record.getMessage() == 'Request successful'] + client_methods = [record.__dict__['client_method'] for record in requests] + assert client_methods == [ + 'StoreCollectionClientAsync.list', + 'StoreCollectionClientAsync.search', + 'StoreCollectionClientAsync.list', + ]