diff --git a/tests/integration/test_actor.py b/tests/integration/test_actor.py index 4263d7ef..f9751d70 100644 --- a/tests/integration/test_actor.py +++ b/tests/integration/test_actor.py @@ -3,23 +3,21 @@ from __future__ import annotations from datetime import UTC, datetime -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING from ._utils import get_random_resource_name, maybe_await +from apify_client._models import Actor, Build, ListOfActors, Run +from apify_client._resource_clients import BuildClient, BuildClientAsync if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Actor, Build, ListOfActors, Run - from apify_client._resource_clients import BuildClient, BuildClientAsync async def test_get_public_actor(client: ApifyClient | ApifyClientAsync) -> None: """Test getting a public Actor by ID.""" # Use a well-known public actor (Apify's web scraper) - result = await maybe_await(client.actor('apify/web-scraper').get()) - actor = cast('Actor', result) - - assert actor is not None + actor = await maybe_await(client.actor('apify/web-scraper').get()) + assert isinstance(actor, Actor) assert actor.id is not None assert actor.name == 'web-scraper' assert actor.username == 'apify' @@ -27,20 +25,16 @@ async def test_get_public_actor(client: ApifyClient | ApifyClientAsync) -> None: async def test_get_actor_by_full_name(client: ApifyClient | ApifyClientAsync) -> None: """Test getting an Actor using username/actorname format.""" - result = await maybe_await(client.actor('apify/hello-world').get()) - actor = cast('Actor', result) - - assert actor is not None + actor = await maybe_await(client.actor('apify/hello-world').get()) + assert isinstance(actor, Actor) assert actor.name == 'hello-world' assert actor.username == 'apify' async def test_list_actors_my(client: ApifyClient | ApifyClientAsync) -> None: """Test listing Actors created by the user.""" - result = await maybe_await(client.actors().list(my=True, limit=10)) - actors_page = cast('ListOfActors', result) - - assert actors_page is not None + actors_page = await maybe_await(client.actors().list(my=True, limit=10)) + assert isinstance(actors_page, ListOfActors) assert actors_page.items is not None # User may have 0 actors assert isinstance(actors_page.items, list) @@ -49,10 +43,8 @@ async def test_list_actors_my(client: ApifyClient | ApifyClientAsync) -> None: async def test_list_actors_pagination(client: ApifyClient | ApifyClientAsync) -> None: """Test listing Actors with pagination parameters.""" # List all actors (public + owned), should return some results - result = await maybe_await(client.actors().list(limit=5, offset=0)) - actors_page = cast('ListOfActors', result) - - assert actors_page is not None + actors_page = await maybe_await(client.actors().list(limit=5, offset=0)) + assert isinstance(actors_page, ListOfActors) assert actors_page.items is not None assert isinstance(actors_page.items, list) # Should have at least some actors (public ones exist) @@ -61,10 +53,8 @@ async def test_list_actors_pagination(client: ApifyClient | ApifyClientAsync) -> async def test_list_actors_sorting(client: ApifyClient | ApifyClientAsync) -> None: """Test listing Actors with sorting.""" - result = await maybe_await(client.actors().list(limit=10, desc=True, sort_by='stats.lastRunStartedAt')) - actors_page = cast('ListOfActors', result) - - assert actors_page is not None + actors_page = await maybe_await(client.actors().list(limit=10, desc=True, sort_by='stats.lastRunStartedAt')) + assert isinstance(actors_page, ListOfActors) assert actors_page.items is not None assert isinstance(actors_page.items, list) @@ -82,7 +72,7 @@ async def test_actor_create_update_delete(client: ApifyClient | ApifyClientAsync actor_name = get_random_resource_name('actor') # Create actor - result = await maybe_await( + created_actor = await maybe_await( client.actors().create( name=actor_name, title='Test Actor', @@ -103,8 +93,7 @@ async def test_actor_create_update_delete(client: ApifyClient | ApifyClientAsync ], ) ) - created_actor = cast('Actor', result) - assert created_actor is not None + assert isinstance(created_actor, Actor) assert created_actor.id is not None assert created_actor.name == actor_name @@ -114,21 +103,19 @@ async def test_actor_create_update_delete(client: ApifyClient | ApifyClientAsync # Update actor (only title and description - updating defaultRunOptions requires build to be set) new_title = 'Updated Test Actor' new_description = 'Updated description' - result = await maybe_await( + updated_actor = await maybe_await( actor_client.update( title=new_title, description=new_description, ) ) - updated_actor = cast('Actor', result) - assert updated_actor is not None + assert isinstance(updated_actor, Actor) assert updated_actor.title == new_title assert updated_actor.description == new_description # Verify update persisted - result = await maybe_await(actor_client.get()) - retrieved_actor = cast('Actor', result) - assert retrieved_actor is not None + retrieved_actor = await maybe_await(actor_client.get()) + assert isinstance(retrieved_actor, Actor) assert retrieved_actor.title == new_title finally: @@ -146,14 +133,12 @@ async def test_actor_default_build(client: ApifyClient | ApifyClientAsync) -> No actor_client = client.actor('apify/hello-world') # Get default build client - result = await maybe_await(actor_client.default_build()) - build_client = cast('BuildClient | BuildClientAsync', result) - assert build_client is not None + build_client = await maybe_await(actor_client.default_build()) + assert isinstance(build_client, BuildClient | BuildClientAsync) # Use the returned client to get the build - result = await maybe_await(build_client.get()) - build = cast('Build', result) - assert build is not None + build = await maybe_await(build_client.get()) + assert isinstance(build, Build) assert build.id is not None assert build.status is not None @@ -162,9 +147,8 @@ async def test_actor_last_run(client: ApifyClient | ApifyClientAsync) -> None: """Test getting an Actor's last run.""" # First run an actor to ensure there is a last run actor_client = client.actor('apify/hello-world') - result = await maybe_await(actor_client.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor_client.call()) + assert isinstance(run, Run) try: # Get last run client @@ -172,9 +156,8 @@ async def test_actor_last_run(client: ApifyClient | ApifyClientAsync) -> None: assert last_run_client is not None # Use the returned client to get the run - result = await maybe_await(last_run_client.get()) - last_run = cast('Run', result) - assert last_run is not None + last_run = await maybe_await(last_run_client.get()) + assert isinstance(last_run, Run) assert last_run.id is not None finally: diff --git a/tests/integration/test_actor_env_var.py b/tests/integration/test_actor_env_var.py index 97011b9c..26c0cbd2 100644 --- a/tests/integration/test_actor_env_var.py +++ b/tests/integration/test_actor_env_var.py @@ -2,14 +2,13 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import get_random_resource_name, maybe_await +from apify_client._models import Actor, EnvVar, ListOfEnvVars if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Actor, EnvVar, ListOfEnvVars - - -from ._utils import get_random_resource_name, maybe_await async def test_actor_env_var_list(client: ApifyClient | ApifyClientAsync) -> None: @@ -17,7 +16,7 @@ async def test_actor_env_var_list(client: ApifyClient | ApifyClientAsync) -> Non actor_name = get_random_resource_name('actor') # Create an actor with a version that has env vars - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -43,16 +42,14 @@ async def test_actor_env_var_list(client: ApifyClient | ApifyClientAsync) -> Non ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) version_client = actor_client.version('0.0') try: # List env vars - result = await maybe_await(version_client.env_vars().list()) - env_vars = cast('ListOfEnvVars', result) - - assert env_vars is not None + env_vars = await maybe_await(version_client.env_vars().list()) + assert isinstance(env_vars, ListOfEnvVars) assert env_vars.items is not None assert len(env_vars.items) >= 1 @@ -70,7 +67,7 @@ async def test_actor_env_var_create_and_get(client: ApifyClient | ApifyClientAsy actor_name = get_random_resource_name('actor') # Create an actor with a version - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -89,32 +86,28 @@ async def test_actor_env_var_create_and_get(client: ApifyClient | ApifyClientAsy ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) version_client = actor_client.version('1.0') try: # Create a new env var - result = await maybe_await( + created_env_var = await maybe_await( version_client.env_vars().create( name='MY_VAR', value='my_value', is_secret=False, ) ) - created_env_var = cast('EnvVar', result) - - assert created_env_var is not None + assert isinstance(created_env_var, EnvVar) assert created_env_var.name == 'MY_VAR' assert created_env_var.value == 'my_value' assert created_env_var.is_secret is False # Get the same env var env_var_client = version_client.env_var('MY_VAR') - result = await maybe_await(env_var_client.get()) - retrieved_env_var = cast('EnvVar', result) - - assert retrieved_env_var is not None + retrieved_env_var = await maybe_await(env_var_client.get()) + assert isinstance(retrieved_env_var, EnvVar) assert retrieved_env_var.name == 'MY_VAR' assert retrieved_env_var.value == 'my_value' @@ -127,7 +120,7 @@ async def test_actor_env_var_update(client: ApifyClient | ApifyClientAsync) -> N actor_name = get_random_resource_name('actor') # Create an actor with a version and env var - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -153,29 +146,26 @@ async def test_actor_env_var_update(client: ApifyClient | ApifyClientAsync) -> N ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) version_client = actor_client.version('0.1') env_var_client = version_client.env_var('UPDATE_VAR') try: # Update the env var - result = await maybe_await( + updated_env_var = await maybe_await( env_var_client.update( name='UPDATE_VAR', value='updated_value', ) ) - updated_env_var = cast('EnvVar', result) - - assert updated_env_var is not None + assert isinstance(updated_env_var, EnvVar) assert updated_env_var.name == 'UPDATE_VAR' assert updated_env_var.value == 'updated_value' # Verify the update persisted - result = await maybe_await(env_var_client.get()) - retrieved_env_var = cast('EnvVar', result) - assert retrieved_env_var is not None + retrieved_env_var = await maybe_await(env_var_client.get()) + assert isinstance(retrieved_env_var, EnvVar) assert retrieved_env_var.value == 'updated_value' finally: @@ -187,7 +177,7 @@ async def test_actor_env_var_delete(client: ApifyClient | ApifyClientAsync) -> N actor_name = get_random_resource_name('actor') # Create an actor with a version and two env vars - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -218,7 +208,7 @@ async def test_actor_env_var_delete(client: ApifyClient | ApifyClientAsync) -> N ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) version_client = actor_client.version('0.1') @@ -232,9 +222,8 @@ async def test_actor_env_var_delete(client: ApifyClient | ApifyClientAsync) -> N assert deleted_env_var is None # Verify the other env var still exists - result = await maybe_await(version_client.env_var('VAR_TO_KEEP').get()) - remaining_env_var = cast('EnvVar', result) - assert remaining_env_var is not None + remaining_env_var = await maybe_await(version_client.env_var('VAR_TO_KEEP').get()) + assert isinstance(remaining_env_var, EnvVar) assert remaining_env_var.name == 'VAR_TO_KEEP' finally: diff --git a/tests/integration/test_actor_version.py b/tests/integration/test_actor_version.py index e0da2754..6b59f447 100644 --- a/tests/integration/test_actor_version.py +++ b/tests/integration/test_actor_version.py @@ -2,14 +2,13 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import get_random_resource_name, maybe_await +from apify_client._models import Actor, ListOfVersions, Version if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Actor, ListOfVersions, Version - - -from ._utils import get_random_resource_name, maybe_await async def test_actor_version_list(client: ApifyClient | ApifyClientAsync) -> None: @@ -17,7 +16,7 @@ async def test_actor_version_list(client: ApifyClient | ApifyClientAsync) -> Non actor_name = get_random_resource_name('actor') # Create an actor with an initial version - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -36,15 +35,13 @@ async def test_actor_version_list(client: ApifyClient | ApifyClientAsync) -> Non ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) try: # List versions - result = await maybe_await(actor_client.versions().list()) - versions = cast('ListOfVersions', result) - - assert versions is not None + versions = await maybe_await(actor_client.versions().list()) + assert isinstance(versions, ListOfVersions) assert versions.items is not None assert len(versions.items) >= 1 @@ -62,13 +59,13 @@ async def test_actor_version_create_and_get(client: ApifyClient | ApifyClientAsy actor_name = get_random_resource_name('actor') # Create an actor without versions - result = await maybe_await(client.actors().create(name=actor_name)) - actor = cast('Actor', result) + actor = await maybe_await(client.actors().create(name=actor_name)) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) try: # Create a new version - result = await maybe_await( + created_version = await maybe_await( actor_client.versions().create( version_number='1.0', source_type='SOURCE_FILES', @@ -82,19 +79,15 @@ async def test_actor_version_create_and_get(client: ApifyClient | ApifyClientAsy ], ) ) - created_version = cast('Version', result) - - assert created_version is not None + assert isinstance(created_version, Version) assert created_version.version_number == '1.0' assert created_version.build_tag == 'test' assert created_version.source_type == 'SOURCE_FILES' # Get the same version version_client = actor_client.version('1.0') - result = await maybe_await(version_client.get()) - retrieved_version = cast('Version | None', result) - - assert retrieved_version is not None + retrieved_version = await maybe_await(version_client.get()) + assert isinstance(retrieved_version, Version) assert retrieved_version.version_number == '1.0' assert retrieved_version.build_tag == 'test' @@ -107,7 +100,7 @@ async def test_actor_version_update(client: ApifyClient | ApifyClientAsync) -> N actor_name = get_random_resource_name('actor') # Create an actor with a version - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -126,13 +119,13 @@ async def test_actor_version_update(client: ApifyClient | ApifyClientAsync) -> N ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) version_client = actor_client.version('0.1') try: # Update the version - result = await maybe_await( + updated_version = await maybe_await( version_client.update( build_tag='updated', source_files=[ @@ -144,16 +137,13 @@ async def test_actor_version_update(client: ApifyClient | ApifyClientAsync) -> N ], ) ) - updated_version = cast('Version', result) - - assert updated_version is not None + assert isinstance(updated_version, Version) assert updated_version.version_number == '0.1' assert updated_version.build_tag == 'updated' # Verify the update persisted - result = await maybe_await(version_client.get()) - retrieved_version = cast('Version | None', result) - assert retrieved_version is not None + retrieved_version = await maybe_await(version_client.get()) + assert isinstance(retrieved_version, Version) assert retrieved_version.build_tag == 'updated' finally: @@ -165,7 +155,7 @@ async def test_actor_version_delete(client: ApifyClient | ApifyClientAsync) -> N actor_name = get_random_resource_name('actor') # Create an actor with two versions - result = await maybe_await( + actor = await maybe_await( client.actors().create( name=actor_name, versions=[ @@ -196,7 +186,7 @@ async def test_actor_version_delete(client: ApifyClient | ApifyClientAsync) -> N ], ) ) - actor = cast('Actor', result) + assert isinstance(actor, Actor) actor_client = client.actor(actor.id) try: @@ -209,9 +199,8 @@ async def test_actor_version_delete(client: ApifyClient | ApifyClientAsync) -> N assert deleted_version is None # Verify version 0.2 still exists - result = await maybe_await(actor_client.version('0.2').get()) - remaining_version = cast('Version | None', result) - assert remaining_version is not None + remaining_version = await maybe_await(actor_client.version('0.2').get()) + assert isinstance(remaining_version, Version) assert remaining_version.version_number == '0.2' finally: diff --git a/tests/integration/test_apify_client.py b/tests/integration/test_apify_client.py index 6bd1bf92..5ec8e940 100644 --- a/tests/integration/test_apify_client.py +++ b/tests/integration/test_apify_client.py @@ -2,19 +2,18 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import maybe_await +from apify_client._models import UserPrivateInfo, UserPublicInfo if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import UserPrivateInfo, UserPublicInfo - - -from ._utils import maybe_await async def test_apify_client(client: ApifyClient | ApifyClientAsync) -> None: """Test basic apify client functionality.""" user_client = client.user('me') - result = await maybe_await(user_client.get()) - me = cast('UserPrivateInfo | UserPublicInfo', result) + me = await maybe_await(user_client.get()) + assert isinstance(me, UserPrivateInfo | UserPublicInfo) assert me.username is not None diff --git a/tests/integration/test_build.py b/tests/integration/test_build.py index 0f10b84c..391a6cf6 100644 --- a/tests/integration/test_build.py +++ b/tests/integration/test_build.py @@ -2,16 +2,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast - -if TYPE_CHECKING: - from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Actor, Build, ListOfBuilds - - from datetime import timedelta +from typing import TYPE_CHECKING from ._utils import get_random_resource_name, maybe_await +from apify_client._models import Actor, Build, ListOfBuilds + +if TYPE_CHECKING: + from apify_client import ApifyClient, ApifyClientAsync # Use a public actor that has builds available HELLO_WORLD_ACTOR = 'apify/hello-world' @@ -21,10 +19,8 @@ async def test_build_list_for_actor(client: ApifyClient | ApifyClientAsync) -> N """Test listing builds for a public Actor.""" # Get builds for hello-world actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.builds().list(limit=10)) - builds_page = cast('ListOfBuilds', result) - - assert builds_page is not None + builds_page = await maybe_await(actor.builds().list(limit=10)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items is not None assert len(builds_page.items) > 0 # hello-world should have at least one build @@ -38,16 +34,14 @@ async def test_build_get(client: ApifyClient | ApifyClientAsync) -> None: """Test getting a specific build.""" # First list builds to get a build ID actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.builds().list(limit=1)) - builds_page = cast('ListOfBuilds', result) + builds_page = await maybe_await(actor.builds().list(limit=1)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items build_id = builds_page.items[0].id # Get the specific build - result = await maybe_await(client.build(build_id).get()) - build = cast('Build | None', result) - - assert build is not None + build = await maybe_await(client.build(build_id).get()) + assert isinstance(build, Build) assert build.id == build_id assert build.act_id is not None assert build.status is not None @@ -56,10 +50,8 @@ async def test_build_get(client: ApifyClient | ApifyClientAsync) -> None: async def test_user_builds_list(client: ApifyClient | ApifyClientAsync) -> None: """Test listing all user builds.""" # List user's builds (may be empty if user has no actors) - result = await maybe_await(client.builds().list(limit=10)) - builds_page = cast('ListOfBuilds', result) - - assert builds_page is not None + builds_page = await maybe_await(client.builds().list(limit=10)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items is not None # User may have 0 builds, so we just check the structure assert isinstance(builds_page.items, list) @@ -69,8 +61,8 @@ async def test_build_log(client: ApifyClient | ApifyClientAsync) -> None: """Test getting build log.""" # First list builds to get a completed build ID actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.builds().list(limit=5)) - builds_page = cast('ListOfBuilds', result) + builds_page = await maybe_await(actor.builds().list(limit=5)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items # Find a completed build (SUCCEEDED status) @@ -96,8 +88,8 @@ async def test_build_wait_for_finish(client: ApifyClient | ApifyClientAsync) -> """Test wait_for_finish on an already completed build.""" # First list builds to get a completed build ID actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.builds().list(limit=5)) - builds_page = cast('ListOfBuilds', result) + builds_page = await maybe_await(actor.builds().list(limit=5)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items # Find a completed build (SUCCEEDED status) @@ -118,10 +110,8 @@ async def test_build_wait_for_finish(client: ApifyClient | ApifyClientAsync) -> completed_build = builds_page.items[0] # Wait for finish on already completed build (should return immediately) - result = await maybe_await(client.build(completed_build.id).wait_for_finish(wait_duration=timedelta(seconds=5))) - build = cast('Build | None', result) - - assert build is not None + build = await maybe_await(client.build(completed_build.id).wait_for_finish(wait_duration=timedelta(seconds=5))) + assert isinstance(build, Build) assert build.id == completed_build.id @@ -130,7 +120,7 @@ async def test_build_delete_and_abort(client: ApifyClient | ApifyClientAsync) -> actor_name = get_random_resource_name('actor') # Create actor with two versions - result = await maybe_await( + created_actor = await maybe_await( client.actors().create( name=actor_name, title='Test Actor for Build Delete', @@ -162,41 +152,35 @@ async def test_build_delete_and_abort(client: ApifyClient | ApifyClientAsync) -> ], ) ) - created_actor = cast('Actor', result) - assert created_actor is not None + assert isinstance(created_actor, Actor) actor_client = client.actor(created_actor.id) try: # Build both versions - we need 2 builds because we can't delete the default build - result = await maybe_await(actor_client.build(version_number='0.1')) - first_build = cast('Build', result) - assert first_build is not None + first_build = await maybe_await(actor_client.build(version_number='0.1')) + assert isinstance(first_build, Build) first_build_client = client.build(first_build.id) await maybe_await(first_build_client.wait_for_finish()) - result = await maybe_await(actor_client.build(version_number='0.2')) - second_build = cast('Build', result) - assert second_build is not None + second_build = await maybe_await(actor_client.build(version_number='0.2')) + assert isinstance(second_build, Build) second_build_client = client.build(second_build.id) # Wait for the second build to finish - result = await maybe_await(second_build_client.wait_for_finish()) - finished_build = cast('Build | None', result) - assert finished_build is not None + finished_build = await maybe_await(second_build_client.wait_for_finish()) + assert isinstance(finished_build, Build) assert finished_build.status in ('SUCCEEDED', 'FAILED') # Test abort on already finished build (should return the build in its current state) - result = await maybe_await(second_build_client.abort()) - aborted_build = cast('Build', result) - assert aborted_build is not None + aborted_build = await maybe_await(second_build_client.abort()) + assert isinstance(aborted_build, Build) assert aborted_build.status in ('SUCCEEDED', 'FAILED') # Delete the first build (not the default/latest) await maybe_await(first_build_client.delete()) # Verify the build is deleted - result = await maybe_await(first_build_client.get()) - deleted_build = cast('Build | None', result) + deleted_build = await maybe_await(first_build_client.get()) assert deleted_build is None finally: @@ -208,8 +192,8 @@ async def test_build_get_open_api_definition(client: ApifyClient | ApifyClientAs """Test getting OpenAPI definition for a build.""" # Get builds for hello-world actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.builds().list(limit=1)) - builds_page = cast('ListOfBuilds', result) + builds_page = await maybe_await(actor.builds().list(limit=1)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items build_id = builds_page.items[0].id diff --git a/tests/integration/test_dataset.py b/tests/integration/test_dataset.py index d2448ea9..4a949ba4 100644 --- a/tests/integration/test_dataset.py +++ b/tests/integration/test_dataset.py @@ -2,8 +2,18 @@ from __future__ import annotations +import json +from datetime import timedelta from typing import TYPE_CHECKING, cast +import impit +import pytest + +from ._utils import DatasetFixture, get_random_resource_name, maybe_await, maybe_sleep +from apify_client._models import Dataset, DatasetStatistics, ListOfDatasets +from apify_client._resource_clients.dataset import DatasetItemsPage +from apify_client.errors import ApifyApiError + if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator from contextlib import AbstractAsyncContextManager, AbstractContextManager @@ -11,35 +21,20 @@ from impit import Response from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Dataset, ListOfDatasets - from apify_client._resource_clients.dataset import DatasetItemsPage - -import json -from datetime import timedelta - -import impit -import pytest - -from ._utils import DatasetFixture, get_random_resource_name, maybe_await, maybe_sleep -from apify_client.errors import ApifyApiError async def test_dataset_collection_list(client: ApifyClient | ApifyClientAsync) -> None: """Test listing datasets.""" - result = await maybe_await(client.datasets().list(limit=10)) - datasets_page = cast('ListOfDatasets', result) - - assert datasets_page is not None + datasets_page = await maybe_await(client.datasets().list(limit=10)) + assert isinstance(datasets_page, ListOfDatasets) assert datasets_page.items is not None assert isinstance(datasets_page.items, list) async def test_dataset_collection_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: """Test listing datasets with pagination.""" - result = await maybe_await(client.datasets().list(limit=5, offset=0)) - datasets_page = cast('ListOfDatasets', result) - - assert datasets_page is not None + datasets_page = await maybe_await(client.datasets().list(limit=5, offset=0)) + assert isinstance(datasets_page, ListOfDatasets) assert datasets_page.items is not None assert isinstance(datasets_page.items, list) @@ -49,16 +44,15 @@ async def test_dataset_collection_get_or_create(client: ApifyClient | ApifyClien unique_name = get_random_resource_name('dataset') # Create new dataset - result = await maybe_await(client.datasets().get_or_create(name=unique_name)) - dataset = cast('Dataset', result) + dataset = await maybe_await(client.datasets().get_or_create(name=unique_name)) + assert isinstance(dataset, Dataset) try: - assert dataset is not None assert dataset.name == unique_name # Get same dataset again (should return existing) - result2 = await maybe_await(client.datasets().get_or_create(name=unique_name)) - same_dataset = cast('Dataset', result2) + same_dataset = await maybe_await(client.datasets().get_or_create(name=unique_name)) + assert isinstance(same_dataset, Dataset) assert same_dataset.id == dataset.id finally: await maybe_await(client.dataset(dataset.id).delete()) @@ -68,21 +62,20 @@ async def test_dataset_should_create_public_items_expiring_url_with_params( client: ApifyClient | ApifyClientAsync, ) -> None: dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset = client.dataset(created_dataset.id) try: - result = await maybe_await( + items_public_url = await maybe_await( dataset.create_items_public_url( expires_in=timedelta(seconds=2000), limit=10, offset=0, ) ) - items_public_url = cast('str', result) - + assert isinstance(items_public_url, str) assert 'signature=' in items_public_url assert 'limit=10' in items_public_url assert 'offset=0' in items_public_url @@ -98,15 +91,14 @@ async def test_dataset_should_create_public_items_non_expiring_url( client: ApifyClient | ApifyClientAsync, ) -> None: dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset = client.dataset(created_dataset.id) try: - result = await maybe_await(dataset.create_items_public_url()) - items_public_url = cast('str', result) - + items_public_url = await maybe_await(dataset.create_items_public_url()) + assert isinstance(items_public_url, str) assert 'signature=' in items_public_url impit_client = impit.Client() @@ -131,8 +123,8 @@ async def test_list_items_signature( # Dataset content retrieved with correct signature signature = test_dataset_of_another_user.signature - result = await maybe_await(dataset.list_items(signature=signature)) - list_items_result = cast('DatasetItemsPage', result) + list_items_result = await maybe_await(dataset.list_items(signature=signature)) + assert isinstance(list_items_result, DatasetItemsPage) assert test_dataset_of_another_user.expected_content == list_items_result.items @@ -185,8 +177,8 @@ async def test_get_items_as_bytes_signature( # Dataset content retrieved with correct signature signature = test_dataset_of_another_user.signature - result = await maybe_await(dataset.get_items_as_bytes(signature=signature)) - raw_data = cast('bytes', result) + raw_data = await maybe_await(dataset.get_items_as_bytes(signature=signature)) + assert isinstance(raw_data, bytes) assert test_dataset_of_another_user.expected_content == json.loads(raw_data.decode('utf-8')) @@ -195,9 +187,8 @@ async def test_dataset_get_or_create_and_get(client: ApifyClient | ApifyClientAs dataset_name = get_random_resource_name('dataset') # Create dataset - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) - assert created_dataset is not None + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) assert created_dataset.id is not None assert created_dataset.name == dataset_name @@ -205,9 +196,8 @@ async def test_dataset_get_or_create_and_get(client: ApifyClient | ApifyClientAs dataset_client = client.dataset(created_dataset.id) try: - result = await maybe_await(dataset_client.get()) - retrieved_dataset = cast('Dataset | None', result) - assert retrieved_dataset is not None + retrieved_dataset = await maybe_await(dataset_client.get()) + assert isinstance(retrieved_dataset, Dataset) assert retrieved_dataset.id == created_dataset.id assert retrieved_dataset.name == dataset_name finally: @@ -219,22 +209,20 @@ async def test_dataset_update(client: ApifyClient | ApifyClientAsync) -> None: dataset_name = get_random_resource_name('dataset') new_name = get_random_resource_name('dataset-updated') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: # Update the name - result = await maybe_await(dataset_client.update(name=new_name)) - updated_dataset = cast('Dataset', result) - assert updated_dataset is not None + updated_dataset = await maybe_await(dataset_client.update(name=new_name)) + assert isinstance(updated_dataset, Dataset) assert updated_dataset.name == new_name assert updated_dataset.id == created_dataset.id # Verify the update persisted - result = await maybe_await(dataset_client.get()) - retrieved_dataset = cast('Dataset | None', result) - assert retrieved_dataset is not None + retrieved_dataset = await maybe_await(dataset_client.get()) + assert isinstance(retrieved_dataset, Dataset) assert retrieved_dataset.name == new_name finally: await maybe_await(dataset_client.delete()) @@ -244,8 +232,8 @@ async def test_dataset_push_and_list_items(client: ApifyClient | ApifyClientAsyn """Test pushing items to dataset and listing them.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: @@ -261,9 +249,8 @@ async def test_dataset_push_and_list_items(client: ApifyClient | ApifyClientAsyn await maybe_sleep(1, is_async=is_async) # List items - result = await maybe_await(dataset_client.list_items()) - items_page = cast('DatasetItemsPage', result) - assert items_page is not None + items_page = await maybe_await(dataset_client.list_items()) + assert isinstance(items_page, DatasetItemsPage) assert len(items_page.items) == 3 assert items_page.count == 3 # Note: items_page.total may be 0 immediately after push due to eventual consistency @@ -281,8 +268,8 @@ async def test_dataset_list_items_with_pagination(client: ApifyClient | ApifyCli """Test listing items with pagination parameters.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: @@ -294,16 +281,16 @@ async def test_dataset_list_items_with_pagination(client: ApifyClient | ApifyCli await maybe_sleep(1, is_async=is_async) # List with limit - result = await maybe_await(dataset_client.list_items(limit=5)) - items_page = cast('DatasetItemsPage', result) + items_page = await maybe_await(dataset_client.list_items(limit=5)) + assert isinstance(items_page, DatasetItemsPage) assert len(items_page.items) == 5 assert items_page.count == 5 # Note: items_page.total may be 0 immediately after push due to eventual consistency assert items_page.limit == 5 # List with offset - result = await maybe_await(dataset_client.list_items(offset=5, limit=5)) - items_page_offset = cast('DatasetItemsPage', result) + items_page_offset = await maybe_await(dataset_client.list_items(offset=5, limit=5)) + assert isinstance(items_page_offset, DatasetItemsPage) assert len(items_page_offset.items) == 5 assert items_page_offset.offset == 5 # Note: items_page.total may be 0 immediately after push due to eventual consistency @@ -318,8 +305,8 @@ async def test_dataset_list_items_with_fields(client: ApifyClient | ApifyClientA """Test listing items with field filtering.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: @@ -334,8 +321,8 @@ async def test_dataset_list_items_with_fields(client: ApifyClient | ApifyClientA await maybe_sleep(1, is_async=is_async) # List with fields filter - result = await maybe_await(dataset_client.list_items(fields=['id', 'name'])) - items_page = cast('DatasetItemsPage', result) + items_page = await maybe_await(dataset_client.list_items(fields=['id', 'name'])) + assert isinstance(items_page, DatasetItemsPage) assert len(items_page.items) == 2 # Verify only specified fields are returned @@ -352,8 +339,8 @@ async def test_dataset_iterate_items(client: ApifyClient | ApifyClientAsync, *, """Test iterating over dataset items.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: @@ -381,16 +368,15 @@ async def test_dataset_delete_nonexistent(client: ApifyClient | ApifyClientAsync """Test that getting a deleted dataset returns None.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) # Delete dataset await maybe_await(dataset_client.delete()) # Verify it's gone - result = await maybe_await(dataset_client.get()) - retrieved_dataset = cast('Dataset | None', result) + retrieved_dataset = await maybe_await(dataset_client.get()) assert retrieved_dataset is None @@ -398,8 +384,8 @@ async def test_dataset_get_statistics(client: ApifyClient | ApifyClientAsync, *, """Test getting dataset statistics.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: @@ -414,11 +400,10 @@ async def test_dataset_get_statistics(client: ApifyClient | ApifyClientAsync, *, await maybe_sleep(1, is_async=is_async) # Get statistics - result = await maybe_await(dataset_client.get_statistics()) - statistics = cast('dict', result) + statistics = await maybe_await(dataset_client.get_statistics()) # Verify statistics is returned and properly parsed - assert statistics is not None + assert isinstance(statistics, DatasetStatistics) finally: await maybe_await(dataset_client.delete()) @@ -428,8 +413,8 @@ async def test_dataset_stream_items(client: ApifyClient | ApifyClientAsync, *, i """Test streaming dataset items.""" dataset_name = get_random_resource_name('dataset') - result = await maybe_await(client.datasets().get_or_create(name=dataset_name)) - created_dataset = cast('Dataset', result) + created_dataset = await maybe_await(client.datasets().get_or_create(name=dataset_name)) + assert isinstance(created_dataset, Dataset) dataset_client = client.dataset(created_dataset.id) try: diff --git a/tests/integration/test_key_value_store.py b/tests/integration/test_key_value_store.py index 1ce2af8d..1e30b9ae 100644 --- a/tests/integration/test_key_value_store.py +++ b/tests/integration/test_key_value_store.py @@ -2,40 +2,36 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast - -if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterator - - from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import KeyValueStore, KeyValueStoreKey, ListOfKeys, ListOfKeyValueStores - import json from datetime import timedelta +from typing import TYPE_CHECKING, cast import impit import pytest from ._utils import KvsFixture, get_random_resource_name, maybe_await, maybe_sleep +from apify_client._models import KeyValueStore, ListOfKeys, ListOfKeyValueStores from apify_client.errors import ApifyApiError +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterator + + from apify_client import ApifyClient, ApifyClientAsync + from apify_client._models import KeyValueStoreKey + async def test_key_value_store_collection_list(client: ApifyClient | ApifyClientAsync) -> None: """Test listing key-value stores.""" - result = await maybe_await(client.key_value_stores().list(limit=10)) - kvs_page = cast('ListOfKeyValueStores', result) - - assert kvs_page is not None + kvs_page = await maybe_await(client.key_value_stores().list(limit=10)) + assert isinstance(kvs_page, ListOfKeyValueStores) assert kvs_page.items is not None assert isinstance(kvs_page.items, list) async def test_key_value_store_collection_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: """Test listing key-value stores with pagination.""" - result = await maybe_await(client.key_value_stores().list(limit=5, offset=0)) - kvs_page = cast('ListOfKeyValueStores', result) - - assert kvs_page is not None + kvs_page = await maybe_await(client.key_value_stores().list(limit=5, offset=0)) + assert isinstance(kvs_page, ListOfKeyValueStores) assert kvs_page.items is not None assert isinstance(kvs_page.items, list) @@ -45,16 +41,15 @@ async def test_key_value_store_collection_get_or_create(client: ApifyClient | Ap unique_name = get_random_resource_name('kvs') # Create new KVS - result = await maybe_await(client.key_value_stores().get_or_create(name=unique_name)) - kvs = cast('KeyValueStore', result) + kvs = await maybe_await(client.key_value_stores().get_or_create(name=unique_name)) + assert isinstance(kvs, KeyValueStore) try: - assert kvs is not None assert kvs.name == unique_name # Get same KVS again (should return existing) - result2 = await maybe_await(client.key_value_stores().get_or_create(name=unique_name)) - same_kvs = cast('KeyValueStore', result2) + same_kvs = await maybe_await(client.key_value_stores().get_or_create(name=unique_name)) + assert isinstance(same_kvs, KeyValueStore) assert same_kvs.id == kvs.id finally: await maybe_await(client.key_value_store(kvs.id).delete()) @@ -64,20 +59,19 @@ async def test_key_value_store_should_create_expiring_keys_public_url_with_param client: ApifyClient | ApifyClientAsync, ) -> None: store_name = get_random_resource_name('key-value-store') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store = client.key_value_store(created_store.id) try: - result = await maybe_await( + keys_public_url = await maybe_await( store.create_keys_public_url( expires_in=timedelta(seconds=2000), limit=10, ) ) - keys_public_url = cast('str', result) - + assert isinstance(keys_public_url, str) assert 'signature=' in keys_public_url assert 'limit=10' in keys_public_url @@ -92,15 +86,14 @@ async def test_key_value_store_should_create_public_keys_non_expiring_url( client: ApifyClient | ApifyClientAsync, ) -> None: store_name = get_random_resource_name('key-value-store') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store = client.key_value_store(created_store.id) try: - result = await maybe_await(store.create_keys_public_url()) - keys_public_url = cast('str', result) - + keys_public_url = await maybe_await(store.create_keys_public_url()) + assert isinstance(keys_public_url, str) assert 'signature=' in keys_public_url impit_client = impit.Client() @@ -124,8 +117,8 @@ async def test_list_keys_signature( await maybe_await(kvs.list_keys()) # Kvs content retrieved with correct signature - result = await maybe_await(kvs.list_keys(signature=test_kvs_of_another_user.signature)) - response = cast('ListOfKeys', result) + response = await maybe_await(kvs.list_keys(signature=test_kvs_of_another_user.signature)) + assert isinstance(response, ListOfKeys) raw_items = response.items assert set(test_kvs_of_another_user.expected_content) == {item.key for item in raw_items} @@ -146,9 +139,8 @@ async def test_get_record_signature( await maybe_await(kvs.get_record(key)) # Kvs content retrieved with correct signature - result = await maybe_await(kvs.get_record(key, signature=test_kvs_of_another_user.keys_signature[key])) - record = cast('dict', result) - assert record + record = await maybe_await(kvs.get_record(key, signature=test_kvs_of_another_user.keys_signature[key])) + assert isinstance(record, dict) assert test_kvs_of_another_user.expected_content[key] == record['value'] @@ -167,9 +159,8 @@ async def test_get_record_as_bytes_signature( await maybe_await(kvs.get_record_as_bytes(key)) # Kvs content retrieved with correct signature - result = await maybe_await(kvs.get_record_as_bytes(key, signature=test_kvs_of_another_user.keys_signature[key])) - item = cast('dict', result) - assert item + item = await maybe_await(kvs.get_record_as_bytes(key, signature=test_kvs_of_another_user.keys_signature[key])) + assert isinstance(item, dict) assert test_kvs_of_another_user.expected_content[key] == json.loads(item['value'].decode('utf-8')) @@ -200,17 +191,15 @@ async def test_stream_record_signature( key, signature=test_kvs_of_another_user.keys_signature[key], ) as stream: # ty: ignore[invalid-context-manager] - assert stream - stream_dict = cast('dict', stream) - value = json.loads(stream_dict['value'].content.decode('utf-8')) + assert isinstance(stream, dict) + value = json.loads(stream['value'].content.decode('utf-8')) else: with kvs.stream_record( key, signature=test_kvs_of_another_user.keys_signature[key], ) as stream: # ty: ignore[invalid-context-manager] - assert stream - stream_dict = cast('dict', stream) - value = json.loads(stream_dict['value'].content.decode('utf-8')) + assert isinstance(stream, dict) + value = json.loads(stream['value'].content.decode('utf-8')) assert test_kvs_of_another_user.expected_content[key] == value @@ -220,9 +209,8 @@ async def test_key_value_store_get_or_create_and_get(client: ApifyClient | Apify store_name = get_random_resource_name('kvs') # Create store - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) - assert created_store is not None + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) assert created_store.id is not None assert created_store.name == store_name @@ -230,9 +218,8 @@ async def test_key_value_store_get_or_create_and_get(client: ApifyClient | Apify store_client = client.key_value_store(created_store.id) try: - result = await maybe_await(store_client.get()) - retrieved_store = cast('KeyValueStore', result) - assert retrieved_store is not None + retrieved_store = await maybe_await(store_client.get()) + assert isinstance(retrieved_store, KeyValueStore) assert retrieved_store.id == created_store.id assert retrieved_store.name == store_name finally: @@ -244,22 +231,20 @@ async def test_key_value_store_update(client: ApifyClient | ApifyClientAsync) -> store_name = get_random_resource_name('kvs') new_name = get_random_resource_name('kvs-updated') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: # Update the name - result = await maybe_await(store_client.update(name=new_name)) - updated_store = cast('KeyValueStore', result) - assert updated_store is not None + updated_store = await maybe_await(store_client.update(name=new_name)) + assert isinstance(updated_store, KeyValueStore) assert updated_store.name == new_name assert updated_store.id == created_store.id # Verify the update persisted - result = await maybe_await(store_client.get()) - retrieved_store = cast('KeyValueStore', result) - assert retrieved_store is not None + retrieved_store = await maybe_await(store_client.get()) + assert isinstance(retrieved_store, KeyValueStore) assert retrieved_store.name == new_name finally: await maybe_await(store_client.delete()) @@ -269,8 +254,8 @@ async def test_key_value_store_set_and_get_record(client: ApifyClient | ApifyCli """Test setting and getting records from key-value store.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -282,9 +267,8 @@ async def test_key_value_store_set_and_get_record(client: ApifyClient | ApifyCli await maybe_sleep(1, is_async=is_async) # Get the record - result = await maybe_await(store_client.get_record('test-key')) - record = cast('dict', result) - assert record is not None + record = await maybe_await(store_client.get_record('test-key')) + assert isinstance(record, dict) assert record['key'] == 'test-key' assert record['value'] == test_value assert 'application/json' in record['content_type'] @@ -298,8 +282,8 @@ async def test_key_value_store_set_and_get_text_record( """Test setting and getting text records.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -311,9 +295,8 @@ async def test_key_value_store_set_and_get_text_record( await maybe_sleep(1, is_async=is_async) # Get the record - result = await maybe_await(store_client.get_record('text-key')) - record = cast('dict', result) - assert record is not None + record = await maybe_await(store_client.get_record('text-key')) + assert isinstance(record, dict) assert record['key'] == 'text-key' assert record['value'] == test_text assert 'text/plain' in record['content_type'] @@ -325,8 +308,8 @@ async def test_key_value_store_list_keys(client: ApifyClient | ApifyClientAsync, """Test listing keys in the key-value store.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -338,9 +321,8 @@ async def test_key_value_store_list_keys(client: ApifyClient | ApifyClientAsync, await maybe_sleep(1, is_async=is_async) # List keys - result = await maybe_await(store_client.list_keys()) - keys_response = cast('ListOfKeys', result) - assert keys_response is not None + keys_response = await maybe_await(store_client.list_keys()) + assert isinstance(keys_response, ListOfKeys) assert len(keys_response.items) == 5 # Verify key names @@ -355,8 +337,8 @@ async def test_key_value_store_list_keys_with_limit(client: ApifyClient | ApifyC """Test listing keys with limit parameter.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -368,9 +350,8 @@ async def test_key_value_store_list_keys_with_limit(client: ApifyClient | ApifyC await maybe_sleep(1, is_async=is_async) # List with limit - result = await maybe_await(store_client.list_keys(limit=5)) - keys_response = cast('ListOfKeys', result) - assert keys_response is not None + keys_response = await maybe_await(store_client.list_keys(limit=5)) + assert isinstance(keys_response, ListOfKeys) assert len(keys_response.items) == 5 finally: await maybe_await(store_client.delete()) @@ -380,8 +361,8 @@ async def test_key_value_store_record_exists(client: ApifyClient | ApifyClientAs """Test checking if a record exists.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -392,10 +373,10 @@ async def test_key_value_store_record_exists(client: ApifyClient | ApifyClientAs await maybe_sleep(1, is_async=is_async) # Check existence - result = await maybe_await(store_client.record_exists('exists-key')) - assert result is True - result = await maybe_await(store_client.record_exists('non-existent-key')) - assert result is False + exists = await maybe_await(store_client.record_exists('exists-key')) + assert exists is True + exists = await maybe_await(store_client.record_exists('non-existent-key')) + assert exists is False finally: await maybe_await(store_client.delete()) @@ -404,8 +385,8 @@ async def test_key_value_store_delete_record(client: ApifyClient | ApifyClientAs """Test deleting a record from the store.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -416,8 +397,8 @@ async def test_key_value_store_delete_record(client: ApifyClient | ApifyClientAs await maybe_sleep(1, is_async=is_async) # Verify it exists - result = await maybe_await(store_client.get_record('delete-me')) - assert result is not None + record = await maybe_await(store_client.get_record('delete-me')) + assert record is not None # Delete the record await maybe_await(store_client.delete_record('delete-me')) @@ -426,8 +407,8 @@ async def test_key_value_store_delete_record(client: ApifyClient | ApifyClientAs await maybe_sleep(1, is_async=is_async) # Verify it's gone - result = await maybe_await(store_client.get_record('delete-me')) - assert result is None + record = await maybe_await(store_client.get_record('delete-me')) + assert record is None finally: await maybe_await(store_client.delete()) @@ -436,16 +417,15 @@ async def test_key_value_store_delete_nonexistent(client: ApifyClient | ApifyCli """Test that getting a deleted store returns None.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) # Delete store await maybe_await(store_client.delete()) # Verify it's gone - result = await maybe_await(store_client.get()) - retrieved_store = cast('KeyValueStore | None', result) + retrieved_store = await maybe_await(store_client.get()) assert retrieved_store is None @@ -453,8 +433,8 @@ async def test_key_value_store_iterate_keys(client: ApifyClient | ApifyClientAsy """Test iterating over keys in the key-value store.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -487,8 +467,8 @@ async def test_key_value_store_iterate_keys_with_limit( """Test iterating over keys with limit parameter.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: @@ -518,8 +498,8 @@ async def test_key_value_store_iterate_keys_with_prefix( """Test iterating over keys with prefix filter.""" store_name = get_random_resource_name('kvs') - result = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) - created_store = cast('KeyValueStore', result) + created_store = await maybe_await(client.key_value_stores().get_or_create(name=store_name)) + assert isinstance(created_store, KeyValueStore) store_client = client.key_value_store(created_store.id) try: diff --git a/tests/integration/test_log.py b/tests/integration/test_log.py index 4f49bc39..84eb09f0 100644 --- a/tests/integration/test_log.py +++ b/tests/integration/test_log.py @@ -2,14 +2,13 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import maybe_await +from apify_client._models import ListOfBuilds, Run if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import ListOfBuilds, Run - - -from ._utils import maybe_await # Use a simple, fast public actor for testing HELLO_WORLD_ACTOR = 'apify/hello-world' @@ -19,9 +18,8 @@ async def test_log_get_from_run(client: ApifyClient | ApifyClientAsync) -> None: """Test retrieving log from an Actor run.""" # Run hello-world actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - assert result is not None - run = cast('Run', result) + run = await maybe_await(actor.call()) + assert isinstance(run, Run) # Get log as text run_client = client.run(run.id) @@ -39,8 +37,8 @@ async def test_log_get_from_build(client: ApifyClient | ApifyClientAsync) -> Non """Test retrieving log from a build.""" # Get a build from hello-world actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.builds().list(limit=1)) - builds_page = cast('ListOfBuilds', result) + builds_page = await maybe_await(actor.builds().list(limit=1)) + assert isinstance(builds_page, ListOfBuilds) assert builds_page.items build_id = builds_page.items[0].id @@ -57,9 +55,8 @@ async def test_log_get_as_bytes(client: ApifyClient | ApifyClientAsync) -> None: """Test retrieving log as raw bytes.""" # Run hello-world actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - assert result is not None - run = cast('Run', result) + run = await maybe_await(actor.call()) + assert isinstance(run, Run) # Get log as bytes run_client = client.run(run.id) diff --git a/tests/integration/test_request_queue.py b/tests/integration/test_request_queue.py index 22c8e3b6..9a100dd6 100644 --- a/tests/integration/test_request_queue.py +++ b/tests/integration/test_request_queue.py @@ -2,47 +2,41 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from datetime import timedelta +from typing import TYPE_CHECKING + +from ._utils import get_random_resource_name, get_random_string, maybe_await, maybe_sleep +from apify_client._models import ( + BatchAddResult, + BatchDeleteResult, + ListOfRequestQueues, + ListOfRequests, + LockedRequestQueueHead, + Request, + RequestLockInfo, + RequestQueue, + RequestQueueHead, + RequestRegistration, + UnlockRequestsResult, +) if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import ( - BatchAddResult, - BatchDeleteResult, - ListOfRequestQueues, - ListOfRequests, - LockedRequestQueueHead, - Request, - RequestLockInfo, - RequestQueue, - RequestQueueHead, - RequestRegistration, - UnlockRequestsResult, - ) from apify_client._typeddicts import RequestDict, RequestDraftDeleteDict, RequestDraftDict -from datetime import timedelta - -from ._utils import get_random_resource_name, get_random_string, maybe_await, maybe_sleep - - async def test_request_queue_collection_list(client: ApifyClient | ApifyClientAsync) -> None: """Test listing request queues.""" - result = await maybe_await(client.request_queues().list(limit=10)) - rq_page = cast('ListOfRequestQueues', result) - - assert rq_page is not None + rq_page = await maybe_await(client.request_queues().list(limit=10)) + assert isinstance(rq_page, ListOfRequestQueues) assert rq_page.items is not None assert isinstance(rq_page.items, list) async def test_request_queue_collection_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: """Test listing request queues with pagination.""" - result = await maybe_await(client.request_queues().list(limit=5, offset=0)) - rq_page = cast('ListOfRequestQueues', result) - - assert rq_page is not None + rq_page = await maybe_await(client.request_queues().list(limit=5, offset=0)) + assert isinstance(rq_page, ListOfRequestQueues) assert rq_page.items is not None assert isinstance(rq_page.items, list) @@ -52,24 +46,23 @@ async def test_request_queue_collection_get_or_create(client: ApifyClient | Apif unique_name = get_random_resource_name('rq') # Create new RQ - result = await maybe_await(client.request_queues().get_or_create(name=unique_name)) - rq = cast('RequestQueue', result) + rq = await maybe_await(client.request_queues().get_or_create(name=unique_name)) + assert isinstance(rq, RequestQueue) try: - assert rq is not None assert rq.name == unique_name # Get same RQ again (should return existing) - result2 = await maybe_await(client.request_queues().get_or_create(name=unique_name)) - same_rq = cast('RequestQueue', result2) + same_rq = await maybe_await(client.request_queues().get_or_create(name=unique_name)) + assert isinstance(same_rq, RequestQueue) assert same_rq.id == rq.id finally: await maybe_await(client.request_queue(rq.id).delete()) async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync, *, is_async: bool) -> None: - result = await maybe_await(client.request_queues().get_or_create(name=get_random_resource_name('queue'))) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=get_random_resource_name('queue'))) + assert isinstance(created_rq, RequestQueue) rq = client.request_queue(created_rq.id, client_key=get_random_string(10)) try: @@ -84,7 +77,8 @@ async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync, *, is_ for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq.list_and_lock_head(limit=10, lock_duration=timedelta(seconds=10))) - get_head_and_lock_response = cast('LockedRequestQueueHead', result) + assert isinstance(result, LockedRequestQueueHead) + get_head_and_lock_response = result if len(get_head_and_lock_response.items) == 10: break @@ -112,14 +106,13 @@ async def test_request_queue_lock(client: ApifyClient | ApifyClientAsync, *, is_ """ # Check if the prolong request works - result = await maybe_await( + prolong_request_lock_response = await maybe_await( rq.prolong_request_lock( get_head_and_lock_response.items[3].id, lock_duration=timedelta(seconds=15), ) ) - prolong_request_lock_response = cast('RequestLockInfo', result) - assert prolong_request_lock_response is not None + assert isinstance(prolong_request_lock_response, RequestLockInfo) assert prolong_request_lock_response.lock_expires_at is not None finally: await maybe_await(rq.delete()) @@ -130,19 +123,17 @@ async def test_request_queue_get_or_create_and_get(client: ApifyClient | ApifyCl rq_name = get_random_resource_name('queue') # Create queue - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: - assert created_rq is not None assert created_rq.id is not None assert created_rq.name == rq_name # Get the same queue - result = await maybe_await(rq_client.get()) - retrieved_rq = cast('RequestQueue', result) - assert retrieved_rq is not None + retrieved_rq = await maybe_await(rq_client.get()) + assert isinstance(retrieved_rq, RequestQueue) assert retrieved_rq.id == created_rq.id assert retrieved_rq.name == rq_name finally: @@ -154,22 +145,20 @@ async def test_request_queue_update(client: ApifyClient | ApifyClientAsync) -> N rq_name = get_random_resource_name('queue') new_name = get_random_resource_name('queue-updated') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: # Update the name - result = await maybe_await(rq_client.update(name=new_name)) - updated_rq = cast('RequestQueue', result) - assert updated_rq is not None + updated_rq = await maybe_await(rq_client.update(name=new_name)) + assert isinstance(updated_rq, RequestQueue) assert updated_rq.name == new_name assert updated_rq.id == created_rq.id # Verify the update persisted - result = await maybe_await(rq_client.get()) - retrieved_rq = cast('RequestQueue', result) - assert retrieved_rq is not None + retrieved_rq = await maybe_await(rq_client.get()) + assert isinstance(retrieved_rq, RequestQueue) assert retrieved_rq.name == new_name finally: await maybe_await(rq_client.delete()) @@ -179,8 +168,8 @@ async def test_request_queue_add_and_get_request(client: ApifyClient | ApifyClie """Test adding and getting a request from the queue.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: @@ -190,9 +179,8 @@ async def test_request_queue_add_and_get_request(client: ApifyClient | ApifyClie 'unique_key': 'test-key-1', 'method': 'GET', } - result = await maybe_await(rq_client.add_request(request_data)) - add_result = cast('RequestRegistration', result) - assert add_result is not None + add_result = await maybe_await(rq_client.add_request(request_data)) + assert isinstance(add_result, RequestRegistration) assert add_result.request_id is not None assert add_result.was_already_present is False @@ -200,9 +188,8 @@ async def test_request_queue_add_and_get_request(client: ApifyClient | ApifyClie await maybe_sleep(1, is_async=is_async) # Get the request - result = await maybe_await(rq_client.get_request(add_result.request_id)) - request = cast('Request', result) - assert request is not None + request = await maybe_await(rq_client.get_request(add_result.request_id)) + assert isinstance(request, Request) assert str(request.url) == 'https://example.com/test' assert request.unique_key == 'test-key-1' finally: @@ -213,8 +200,8 @@ async def test_request_queue_list_head(client: ApifyClient | ApifyClientAsync, * """Test listing requests from the head of the queue.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: @@ -229,7 +216,8 @@ async def test_request_queue_list_head(client: ApifyClient | ApifyClientAsync, * for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_head(limit=3)) - head_response = cast('RequestQueueHead', result) + assert isinstance(result, RequestQueueHead) + head_response = result if len(head_response.items) == 3: break @@ -243,8 +231,8 @@ async def test_request_queue_list_requests(client: ApifyClient | ApifyClientAsyn """Test listing all requests in the queue.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: @@ -259,7 +247,8 @@ async def test_request_queue_list_requests(client: ApifyClient | ApifyClientAsyn for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_requests()) - list_response = cast('ListOfRequests', result) + assert isinstance(result, ListOfRequests) + list_response = result if len(list_response.items) == 5: break @@ -273,16 +262,16 @@ async def test_request_queue_delete_request(client: ApifyClient | ApifyClientAsy """Test deleting a request from the queue.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: # Add a request - result = await maybe_await( + add_result = await maybe_await( rq_client.add_request({'url': 'https://example.com/to-delete', 'unique_key': 'delete-me'}) ) - add_result = cast('RequestRegistration', result) + assert isinstance(add_result, RequestRegistration) # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) @@ -308,8 +297,8 @@ async def test_request_queue_batch_add_requests(client: ApifyClient | ApifyClien """Test adding multiple requests in batch.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: @@ -317,9 +306,8 @@ async def test_request_queue_batch_add_requests(client: ApifyClient | ApifyClien requests_to_add: list[RequestDraftDict] = [ {'url': f'https://example.com/batch-{i}', 'unique_key': f'batch-{i}'} for i in range(10) ] - result = await maybe_await(rq_client.batch_add_requests(requests_to_add)) - batch_response = cast('BatchAddResult', result) - assert batch_response is not None + batch_response = await maybe_await(rq_client.batch_add_requests(requests_to_add)) + assert isinstance(batch_response, BatchAddResult) assert len(batch_response.processed_requests) == 10 assert len(batch_response.unprocessed_requests) == 0 @@ -328,7 +316,8 @@ async def test_request_queue_batch_add_requests(client: ApifyClient | ApifyClien for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_requests()) - list_response = cast('ListOfRequests', result) + assert isinstance(result, ListOfRequests) + list_response = result if len(list_response.items) == 10: break @@ -342,8 +331,8 @@ async def test_request_queue_batch_delete_requests(client: ApifyClient | ApifyCl """Test deleting multiple requests in batch.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: @@ -358,7 +347,8 @@ async def test_request_queue_batch_delete_requests(client: ApifyClient | ApifyCl for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_requests()) - list_response = cast('ListOfRequests', result) + assert isinstance(result, ListOfRequests) + list_response = result if len(list_response.items) == 10: break @@ -370,9 +360,8 @@ async def test_request_queue_batch_delete_requests(client: ApifyClient | ApifyCl requests_to_delete.append({'unique_key': item.unique_key}) # Batch delete - result = await maybe_await(rq_client.batch_delete_requests(requests_to_delete)) - delete_response = cast('BatchDeleteResult', result) - assert delete_response is not None + delete_response = await maybe_await(rq_client.batch_delete_requests(requests_to_delete)) + assert isinstance(delete_response, BatchDeleteResult) assert len(delete_response.processed_requests) == 5 # Poll until deletions are reflected (eventual consistency) @@ -380,7 +369,8 @@ async def test_request_queue_batch_delete_requests(client: ApifyClient | ApifyCl for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_requests()) - remaining = cast('ListOfRequests', result) + assert isinstance(result, ListOfRequests) + remaining = result if len(remaining.items) == 5: break @@ -394,8 +384,8 @@ async def test_request_queue_delete_nonexistent(client: ApifyClient | ApifyClien """Test that getting a deleted queue returns None.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) # Delete queue @@ -410,8 +400,8 @@ async def test_request_queue_list_and_lock_head(client: ApifyClient | ApifyClien """Test locking requests from the head of the queue.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) try: @@ -426,7 +416,8 @@ async def test_request_queue_list_and_lock_head(client: ApifyClient | ApifyClien for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_and_lock_head(limit=3, lock_duration=timedelta(seconds=60))) - lock_response = cast('LockedRequestQueueHead', result) + assert isinstance(result, LockedRequestQueueHead) + lock_response = result if len(lock_response.items) == 3: break @@ -445,8 +436,8 @@ async def test_request_queue_prolong_request_lock(client: ApifyClient | ApifyCli """Test prolonging a request lock.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) try: @@ -458,7 +449,8 @@ async def test_request_queue_prolong_request_lock(client: ApifyClient | ApifyCli for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_and_lock_head(limit=1, lock_duration=timedelta(seconds=60))) - lock_response = cast('LockedRequestQueueHead', result) + assert isinstance(result, LockedRequestQueueHead) + lock_response = result if len(lock_response.items) == 1: break @@ -468,11 +460,10 @@ async def test_request_queue_prolong_request_lock(client: ApifyClient | ApifyCli original_lock_expires = locked_request.lock_expires_at # Prolong the lock - result = await maybe_await( + prolong_response = await maybe_await( rq_client.prolong_request_lock(locked_request.id, lock_duration=timedelta(seconds=120)) ) - prolong_response = cast('RequestLockInfo', result) - assert prolong_response is not None + assert isinstance(prolong_response, RequestLockInfo) assert prolong_response.lock_expires_at is not None assert prolong_response.lock_expires_at > original_lock_expires finally: @@ -483,8 +474,8 @@ async def test_request_queue_delete_request_lock(client: ApifyClient | ApifyClie """Test deleting a request lock.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) try: @@ -496,7 +487,8 @@ async def test_request_queue_delete_request_lock(client: ApifyClient | ApifyClie for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_and_lock_head(limit=1, lock_duration=timedelta(seconds=60))) - lock_response = cast('LockedRequestQueueHead', result) + assert isinstance(result, LockedRequestQueueHead) + lock_response = result if len(lock_response.items) == 1: break @@ -519,8 +511,8 @@ async def test_request_queue_unlock_requests(client: ApifyClient | ApifyClientAs """Test unlocking all requests locked by the client.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id, client_key=get_random_string(10)) try: @@ -535,7 +527,8 @@ async def test_request_queue_unlock_requests(client: ApifyClient | ApifyClientAs for _ in range(5): await maybe_sleep(1, is_async=is_async) result = await maybe_await(rq_client.list_and_lock_head(limit=3, lock_duration=timedelta(seconds=60))) - lock_response = cast('LockedRequestQueueHead', result) + assert isinstance(result, LockedRequestQueueHead) + lock_response = result if len(lock_response.items) == 3: break @@ -543,9 +536,8 @@ async def test_request_queue_unlock_requests(client: ApifyClient | ApifyClientAs assert len(lock_response.items) == 3 # Unlock all requests - result = await maybe_await(rq_client.unlock_requests()) - unlock_response = cast('UnlockRequestsResult', result) - assert unlock_response is not None + unlock_response = await maybe_await(rq_client.unlock_requests()) + assert isinstance(unlock_response, UnlockRequestsResult) assert unlock_response.unlocked_count == 3 finally: await maybe_await(rq_client.delete()) @@ -555,8 +547,8 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy """Test updating a request in the queue.""" rq_name = get_random_resource_name('queue') - result = await maybe_await(client.request_queues().get_or_create(name=rq_name)) - created_rq = cast('RequestQueue', result) + created_rq = await maybe_await(client.request_queues().get_or_create(name=rq_name)) + assert isinstance(created_rq, RequestQueue) rq_client = client.request_queue(created_rq.id) try: @@ -566,18 +558,16 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy 'unique_key': 'update-test', 'method': 'GET', } - result = await maybe_await(rq_client.add_request(request_data)) - add_result = cast('RequestRegistration', result) - assert add_result is not None + add_result = await maybe_await(rq_client.add_request(request_data)) + assert isinstance(add_result, RequestRegistration) assert add_result.request_id is not None # Wait briefly for eventual consistency await maybe_sleep(1, is_async=is_async) # Get the request to get its full data - result = await maybe_await(rq_client.get_request(add_result.request_id)) - original_request = cast('Request', result) - assert original_request is not None + original_request = await maybe_await(rq_client.get_request(add_result.request_id)) + assert isinstance(original_request, Request) assert original_request.unique_key is not None # Update the request (change method and add user data) @@ -588,9 +578,8 @@ async def test_request_queue_update_request(client: ApifyClient | ApifyClientAsy 'method': 'POST', 'user_data': {'updated': True}, } - result = await maybe_await(rq_client.update_request(updated_request_data)) - update_result = cast('RequestRegistration', result) - assert update_result is not None + update_result = await maybe_await(rq_client.update_request(updated_request_data)) + assert isinstance(update_result, RequestRegistration) assert update_result.request_id == add_result.request_id finally: await maybe_await(rq_client.delete()) diff --git a/tests/integration/test_run.py b/tests/integration/test_run.py index 20b3045e..9cfd24fb 100644 --- a/tests/integration/test_run.py +++ b/tests/integration/test_run.py @@ -2,19 +2,16 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast - -if TYPE_CHECKING: - from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Dataset, KeyValueStore, ListOfRuns, RequestQueue, Run - - from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING from ._utils import maybe_await, maybe_sleep -from apify_client._models import Run +from apify_client._models import Dataset, KeyValueStore, ListOfRuns, RequestQueue, Run from apify_client.errors import ApifyApiError +if TYPE_CHECKING: + from apify_client import ApifyClient, ApifyClientAsync + HELLO_WORLD_ACTOR = 'apify/hello-world' @@ -22,27 +19,24 @@ async def test_run_collection_list_multiple_statuses(client: ApifyClient | Apify """Test listing runs with multiple statuses.""" created_runs = list[Run]() - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call()) - if result is not None: - successful_run = cast('Run', result) + successful_run = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call()) + if successful_run is not None: + assert isinstance(successful_run, Run) created_runs.append(successful_run) - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) - if result is not None: - timed_out_run = cast('Run', result) + timed_out_run = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) + if timed_out_run is not None: + assert isinstance(timed_out_run, Run) created_runs.append(timed_out_run) try: run_collection = client.actor(HELLO_WORLD_ACTOR).runs() - result = await maybe_await(run_collection.list(status=['SUCCEEDED', 'TIMED-OUT'])) - multiple_status_runs = cast('ListOfRuns', result) + multiple_status_runs = await maybe_await(run_collection.list(status=['SUCCEEDED', 'TIMED-OUT'])) + assert isinstance(multiple_status_runs, ListOfRuns) - result = await maybe_await(run_collection.list(status='SUCCEEDED')) - single_status_runs = cast('ListOfRuns', result) - - assert multiple_status_runs is not None - assert single_status_runs is not None + single_status_runs = await maybe_await(run_collection.list(status='SUCCEEDED')) + assert isinstance(single_status_runs, ListOfRuns) assert all(run.status in ['SUCCEEDED', 'TIMED-OUT'] for run in multiple_status_runs.items) assert all(run.status == 'SUCCEEDED' for run in single_status_runs.items) @@ -57,14 +51,14 @@ async def test_run_collection_list_accept_date_range(client: ApifyClient | Apify """Test listing runs with date range parameters.""" created_runs = list[Run]() - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call()) - if result is not None: - successful_run = cast('Run', result) + successful_run = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call()) + if successful_run is not None: + assert isinstance(successful_run, Run) created_runs.append(successful_run) - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) - if result is not None: - timed_out_run = cast('Run', result) + timed_out_run = await maybe_await(client.actor(HELLO_WORLD_ACTOR).call(timeout=timedelta(seconds=1))) + if timed_out_run is not None: + assert isinstance(timed_out_run, Run) created_runs.append(timed_out_run) try: @@ -88,15 +82,13 @@ async def test_run_get_and_delete(client: ApifyClient | ApifyClientAsync) -> Non """Test getting and deleting a run.""" # Run actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) # Get the run run_client = client.run(run.id) - result = await maybe_await(run_client.get()) - retrieved_run = cast('Run', result) - assert retrieved_run is not None + retrieved_run = await maybe_await(run_client.get()) + assert isinstance(retrieved_run, Run) assert retrieved_run.id == run.id assert retrieved_run.status == 'SUCCEEDED' @@ -112,9 +104,8 @@ async def test_run_dataset(client: ApifyClient | ApifyClientAsync) -> None: """Test accessing run's default dataset.""" # Run actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) # Access run's dataset run_client = client.run(run.id) @@ -123,9 +114,8 @@ async def test_run_dataset(client: ApifyClient | ApifyClientAsync) -> None: dataset_client = run_client.dataset() # Get dataset info - result = await maybe_await(dataset_client.get()) - dataset = cast('Dataset', result) - assert dataset is not None + dataset = await maybe_await(dataset_client.get()) + assert isinstance(dataset, Dataset) assert dataset.id == run.default_dataset_id finally: await maybe_await(run_client.delete()) @@ -135,9 +125,8 @@ async def test_run_key_value_store(client: ApifyClient | ApifyClientAsync) -> No """Test accessing run's default key-value store.""" # Run actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) # Access run's key-value store run_client = client.run(run.id) @@ -146,9 +135,8 @@ async def test_run_key_value_store(client: ApifyClient | ApifyClientAsync) -> No kvs_client = run_client.key_value_store() # Get KVS info - result = await maybe_await(kvs_client.get()) - kvs = cast('KeyValueStore', result) - assert kvs is not None + kvs = await maybe_await(kvs_client.get()) + assert isinstance(kvs, KeyValueStore) assert kvs.id == run.default_key_value_store_id finally: await maybe_await(run_client.delete()) @@ -158,9 +146,8 @@ async def test_run_request_queue(client: ApifyClient | ApifyClientAsync) -> None """Test accessing run's default request queue.""" # Run actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) # Access run's request queue run_client = client.run(run.id) @@ -169,9 +156,8 @@ async def test_run_request_queue(client: ApifyClient | ApifyClientAsync) -> None rq_client = run_client.request_queue() # Get RQ info - result = await maybe_await(rq_client.get()) - rq = cast('RequestQueue', result) - assert rq is not None + rq = await maybe_await(rq_client.get()) + assert isinstance(rq, RequestQueue) assert rq.id == run.default_request_queue_id finally: await maybe_await(run_client.delete()) @@ -181,26 +167,22 @@ async def test_run_abort(client: ApifyClient | ApifyClientAsync) -> None: """Test aborting a running Actor.""" # Start actor without waiting actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.start()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.start()) + assert isinstance(run, Run) assert run.id is not None # Abort the run run_client = client.run(run.id) try: - result = await maybe_await(run_client.abort()) - aborted_run = cast('Run', result) - - assert aborted_run is not None + aborted_run = await maybe_await(run_client.abort()) + assert isinstance(aborted_run, Run) # Status should be ABORTING or ABORTED (or SUCCEEDED if too fast) assert aborted_run.status in ['ABORTING', 'ABORTED', 'SUCCEEDED'] # Wait for abort to complete - result = await maybe_await(run_client.wait_for_finish()) - final_run = cast('Run', result) - assert final_run is not None + final_run = await maybe_await(run_client.wait_for_finish()) + assert isinstance(final_run, Run) assert final_run.status in ['ABORTED', 'SUCCEEDED'] finally: await maybe_await(run_client.wait_for_finish()) @@ -211,22 +193,20 @@ async def test_run_update(client: ApifyClient | ApifyClientAsync) -> None: """Test updating a run's status message.""" # Run actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) run_client = client.run(run.id) try: # Update run status message - result = await maybe_await( + updated_run = await maybe_await( run_client.update( status_message='Test status message', is_status_message_terminal=True, ) ) - updated_run = cast('Run', result) - assert updated_run is not None + assert isinstance(updated_run, Run) assert updated_run.status_message == 'Test status message' finally: @@ -237,25 +217,22 @@ async def test_run_resurrect(client: ApifyClient | ApifyClientAsync) -> None: """Test resurrecting a finished run.""" # Run actor and wait for it to finish actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) assert run.status == 'SUCCEEDED' run_client = client.run(run.id) try: # Resurrect the run - result = await maybe_await(run_client.resurrect()) - resurrected_run = cast('Run', result) - assert resurrected_run is not None + resurrected_run = await maybe_await(run_client.resurrect()) + assert isinstance(resurrected_run, Run) # Status should be READY, RUNNING or already finished (if fast) assert resurrected_run.status in ['READY', 'RUNNING', 'SUCCEEDED'] # Wait for it to finish before deleting - result = await maybe_await(run_client.wait_for_finish()) - final_run = cast('Run', result) - assert final_run is not None + final_run = await maybe_await(run_client.wait_for_finish()) + assert isinstance(final_run, Run) assert final_run.status == 'SUCCEEDED' finally: @@ -268,9 +245,8 @@ async def test_run_log(client: ApifyClient | ApifyClientAsync) -> None: """Test accessing run's log.""" # Run actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) run_client = client.run(run.id) @@ -279,9 +255,8 @@ async def test_run_log(client: ApifyClient | ApifyClientAsync) -> None: log_client = run_client.log() # Get log content - result = await maybe_await(log_client.get()) - log_content = cast('str', result) - assert log_content is not None + log_content = await maybe_await(log_client.get()) + assert isinstance(log_content, str) # Log should contain something (at least actor startup messages) assert len(log_content) > 0 @@ -292,9 +267,8 @@ async def test_run_log(client: ApifyClient | ApifyClientAsync) -> None: async def test_run_runs_client(client: ApifyClient | ApifyClientAsync) -> None: """Test listing runs through the run collection client.""" # List runs (should return valid data structure) - result = await maybe_await(client.runs().list(limit=10)) - runs_page = cast('ListOfRuns', result) - assert runs_page is not None + runs_page = await maybe_await(client.runs().list(limit=10)) + assert isinstance(runs_page, ListOfRuns) assert runs_page.items is not None assert isinstance(runs_page.items, list) # The user may have runs, verify the structure @@ -308,9 +282,8 @@ async def test_run_metamorph(client: ApifyClient | ApifyClientAsync, *, is_async """Test metamorphing a run into another Actor.""" # Start an actor that will run long enough to metamorph. We use hello-world and try to metamorph it into itself actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.start()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.start()) + assert isinstance(run, Run) assert run.id is not None run_client = client.run(run.id) @@ -322,20 +295,18 @@ async def test_run_metamorph(client: ApifyClient | ApifyClientAsync, *, is_async # Metamorph the run into the same actor (allowed) with new input # Note: hello-world may finish before we can metamorph, so we handle that case try: - result = await maybe_await( + metamorphed_run = await maybe_await( run_client.metamorph( target_actor_id=HELLO_WORLD_ACTOR, run_input={'message': 'Hello from metamorph!'}, ) ) - metamorphed_run = cast('Run', result) - assert metamorphed_run is not None + assert isinstance(metamorphed_run, Run) assert metamorphed_run.id == run.id # Same run ID # Wait for the metamorphed run to finish - result = await maybe_await(run_client.wait_for_finish()) - final_run = cast('Run', result) - assert final_run is not None + final_run = await maybe_await(run_client.wait_for_finish()) + assert isinstance(final_run, Run) except ApifyApiError as exc: # If the actor finished before we could metamorph, that's OK - the test still verified the API call if 'already finished' not in str(exc): @@ -350,9 +321,8 @@ async def test_run_reboot(client: ApifyClient | ApifyClientAsync, *, is_async: b """Test rebooting a running Actor.""" # Start an actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.start()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.start()) + assert isinstance(run, Run) assert run.id is not None run_client = client.run(run.id) @@ -360,16 +330,14 @@ async def test_run_reboot(client: ApifyClient | ApifyClientAsync, *, is_async: b try: # Wait a bit and check if the run is still running await maybe_sleep(1, is_async=is_async) - result = await maybe_await(run_client.get()) - current_run = cast('Run | None', result) + current_run = await maybe_await(run_client.get()) # Only try to reboot if the run is still running # Note: There's a race condition - run may finish between check and reboot call - if current_run and current_run.status == 'RUNNING': + if isinstance(current_run, Run) and current_run.status == 'RUNNING': try: - result = await maybe_await(run_client.reboot()) - rebooted_run = cast('Run', result) - assert rebooted_run is not None + rebooted_run = await maybe_await(run_client.reboot()) + assert isinstance(rebooted_run, Run) assert rebooted_run.id == run.id except ApifyApiError as exc: # If the actor finished before we could reboot, that's OK @@ -377,9 +345,8 @@ async def test_run_reboot(client: ApifyClient | ApifyClientAsync, *, is_async: b raise # Wait for the run to finish - result = await maybe_await(run_client.wait_for_finish()) - final_run = cast('Run', result) - assert final_run is not None + final_run = await maybe_await(run_client.wait_for_finish()) + assert isinstance(final_run, Run) finally: await maybe_await(run_client.wait_for_finish()) @@ -394,9 +361,8 @@ async def test_run_charge(client: ApifyClient | ApifyClientAsync) -> None: """ # Run an actor actor = client.actor(HELLO_WORLD_ACTOR) - result = await maybe_await(actor.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(actor.call()) + assert isinstance(run, Run) run_client = client.run(run.id) diff --git a/tests/integration/test_schedule.py b/tests/integration/test_schedule.py index 0c2bc8a0..1cf4f95d 100644 --- a/tests/integration/test_schedule.py +++ b/tests/integration/test_schedule.py @@ -2,14 +2,13 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import get_random_resource_name, maybe_await +from apify_client._models import ListOfSchedules, Schedule if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import ListOfSchedules, Schedule - - -from ._utils import get_random_resource_name, maybe_await async def test_schedule_create_and_get(client: ApifyClient | ApifyClientAsync) -> None: @@ -17,7 +16,7 @@ async def test_schedule_create_and_get(client: ApifyClient | ApifyClientAsync) - schedule_name = get_random_resource_name('schedule') # Create schedule - result = await maybe_await( + created_schedule = await maybe_await( client.schedules().create( cron_expression='0 0 * * *', is_enabled=False, @@ -25,11 +24,10 @@ async def test_schedule_create_and_get(client: ApifyClient | ApifyClientAsync) - name=schedule_name, ) ) - created_schedule = cast('Schedule', result) + assert isinstance(created_schedule, Schedule) schedule_client = client.schedule(created_schedule.id) try: - assert created_schedule is not None assert created_schedule.id is not None assert created_schedule.name == schedule_name assert created_schedule.cron_expression == '0 0 * * *' @@ -37,9 +35,8 @@ async def test_schedule_create_and_get(client: ApifyClient | ApifyClientAsync) - assert created_schedule.is_exclusive is False # Get the same schedule - result = await maybe_await(schedule_client.get()) - retrieved_schedule = cast('Schedule', result) - assert retrieved_schedule is not None + retrieved_schedule = await maybe_await(schedule_client.get()) + assert isinstance(retrieved_schedule, Schedule) assert retrieved_schedule.id == created_schedule.id assert retrieved_schedule.name == schedule_name finally: @@ -52,7 +49,7 @@ async def test_schedule_update(client: ApifyClient | ApifyClientAsync) -> None: new_name = get_random_resource_name('schedule-updated') # Create schedule - result = await maybe_await( + created_schedule = await maybe_await( client.schedules().create( cron_expression='0 0 * * *', is_enabled=False, @@ -60,29 +57,27 @@ async def test_schedule_update(client: ApifyClient | ApifyClientAsync) -> None: name=schedule_name, ) ) - created_schedule = cast('Schedule', result) + assert isinstance(created_schedule, Schedule) schedule_client = client.schedule(created_schedule.id) try: # Update the schedule - result = await maybe_await( + updated_schedule = await maybe_await( schedule_client.update( name=new_name, cron_expression='0 12 * * *', is_enabled=True, ) ) - updated_schedule = cast('Schedule', result) - assert updated_schedule is not None + assert isinstance(updated_schedule, Schedule) assert updated_schedule.name == new_name assert updated_schedule.cron_expression == '0 12 * * *' assert updated_schedule.is_enabled is True assert updated_schedule.id == created_schedule.id # Verify the update persisted - result = await maybe_await(schedule_client.get()) - retrieved_schedule = cast('Schedule', result) - assert retrieved_schedule is not None + retrieved_schedule = await maybe_await(schedule_client.get()) + assert isinstance(retrieved_schedule, Schedule) assert retrieved_schedule.name == new_name assert retrieved_schedule.cron_expression == '0 12 * * *' finally: @@ -95,7 +90,7 @@ async def test_schedule_list(client: ApifyClient | ApifyClientAsync) -> None: schedule_name_2 = get_random_resource_name('schedule') # Create two schedules - result = await maybe_await( + created_1 = await maybe_await( client.schedules().create( cron_expression='0 0 * * *', is_enabled=False, @@ -103,8 +98,8 @@ async def test_schedule_list(client: ApifyClient | ApifyClientAsync) -> None: name=schedule_name_1, ) ) - created_1 = cast('Schedule', result) - result = await maybe_await( + assert isinstance(created_1, Schedule) + created_2 = await maybe_await( client.schedules().create( cron_expression='0 6 * * *', is_enabled=False, @@ -112,13 +107,12 @@ async def test_schedule_list(client: ApifyClient | ApifyClientAsync) -> None: name=schedule_name_2, ) ) - created_2 = cast('Schedule', result) + assert isinstance(created_2, Schedule) try: # List schedules - result = await maybe_await(client.schedules().list(limit=100)) - schedules_page = cast('ListOfSchedules', result) - assert schedules_page is not None + schedules_page = await maybe_await(client.schedules().list(limit=100)) + assert isinstance(schedules_page, ListOfSchedules) assert schedules_page.items is not None # Verify our schedules are in the list @@ -135,7 +129,7 @@ async def test_schedule_delete(client: ApifyClient | ApifyClientAsync) -> None: schedule_name = get_random_resource_name('schedule') # Create schedule - result = await maybe_await( + created_schedule = await maybe_await( client.schedules().create( cron_expression='0 0 * * *', is_enabled=False, @@ -143,7 +137,7 @@ async def test_schedule_delete(client: ApifyClient | ApifyClientAsync) -> None: name=schedule_name, ) ) - created_schedule = cast('Schedule', result) + assert isinstance(created_schedule, Schedule) schedule_client = client.schedule(created_schedule.id) # Delete schedule @@ -159,7 +153,7 @@ async def test_schedule_get_log(client: ApifyClient | ApifyClientAsync) -> None: schedule_name = get_random_resource_name('schedule') # Create schedule - result = await maybe_await( + created_schedule = await maybe_await( client.schedules().create( cron_expression='0 0 * * *', is_enabled=False, @@ -167,7 +161,7 @@ async def test_schedule_get_log(client: ApifyClient | ApifyClientAsync) -> None: name=schedule_name, ) ) - created_schedule = cast('Schedule', result) + assert isinstance(created_schedule, Schedule) schedule_client = client.schedule(created_schedule.id) try: diff --git a/tests/integration/test_store.py b/tests/integration/test_store.py index 44959e1c..1ca17f69 100644 --- a/tests/integration/test_store.py +++ b/tests/integration/test_store.py @@ -2,44 +2,37 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import maybe_await +from apify_client._models import ListOfStoreActors if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import ListOfStoreActors - - -from ._utils import maybe_await async def test_store_list(client: ApifyClient | ApifyClientAsync) -> None: """Test listing public Actors in the store.""" - result = await maybe_await(client.store().list(limit=10)) - actors_list = cast('ListOfStoreActors', result) - assert actors_list is not None + 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 async def test_store_list_with_search(client: ApifyClient | ApifyClientAsync) -> None: """Test listing store with search filter.""" - result = await maybe_await(client.store().list(limit=5, search='web scraper')) - store_page = cast('ListOfStoreActors', result) - - assert store_page is not None + 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) async def test_store_list_pagination(client: ApifyClient | ApifyClientAsync) -> None: """Test store listing pagination.""" - result1 = await maybe_await(client.store().list(limit=5, offset=0)) - result2 = await maybe_await(client.store().list(limit=5, offset=5)) - page1 = cast('ListOfStoreActors', result1) - page2 = cast('ListOfStoreActors', result2) - - assert page1 is not None - assert page2 is not None + 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) + assert isinstance(page2, ListOfStoreActors) # Verify different results (if enough actors exist) if len(page1.items) == 5 and len(page2.items) > 0: assert page1.items[0].id != page2.items[0].id diff --git a/tests/integration/test_task.py b/tests/integration/test_task.py index d6dadb39..14c8f8f9 100644 --- a/tests/integration/test_task.py +++ b/tests/integration/test_task.py @@ -3,13 +3,13 @@ from __future__ import annotations from datetime import timedelta -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING from ._utils import get_random_resource_name, maybe_await +from apify_client._models import Actor, ListOfRuns, ListOfTasks, ListOfWebhooks, Run, Task if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import Actor, ListOfRuns, ListOfTasks, ListOfWebhooks, Run, Task # Use a simple, fast public actor for testing HELLO_WORLD_ACTOR = 'apify/hello-world' @@ -20,31 +20,28 @@ async def test_task_create_and_get(client: ApifyClient | ApifyClientAsync) -> No task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) actor_id = actor.id # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor_id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: - assert created_task is not None assert created_task.id is not None assert created_task.name == task_name assert created_task.act_id == actor_id # Get the same task - result = await maybe_await(task_client.get()) - retrieved_task = cast('Task', result) - assert retrieved_task is not None + retrieved_task = await maybe_await(task_client.get()) + assert isinstance(retrieved_task, Task) assert retrieved_task.id == created_task.id assert retrieved_task.name == task_name finally: @@ -57,37 +54,34 @@ async def test_task_update(client: ApifyClient | ApifyClientAsync) -> None: new_name = get_random_resource_name('task-updated') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Update the task - result = await maybe_await( + updated_task = await maybe_await( task_client.update( name=new_name, timeout=timedelta(seconds=300), ) ) - updated_task = cast('Task', result) - assert updated_task is not None + assert isinstance(updated_task, Task) assert updated_task.name == new_name assert updated_task.id == created_task.id # Verify the update persisted - result = await maybe_await(task_client.get()) - retrieved_task = cast('Task', result) - assert retrieved_task is not None + retrieved_task = await maybe_await(task_client.get()) + assert isinstance(retrieved_task, Task) assert retrieved_task.name == new_name finally: await maybe_await(task_client.delete()) @@ -98,24 +92,22 @@ async def test_task_list(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create a task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) try: # List tasks - result = await maybe_await(client.tasks().list(limit=100)) - tasks_page = cast('ListOfTasks', result) - assert tasks_page is not None + tasks_page = await maybe_await(client.tasks().list(limit=100)) + assert isinstance(tasks_page, ListOfTasks) assert tasks_page.items is not None # Verify our task is in the list @@ -131,33 +123,30 @@ async def test_task_get_input(client: ApifyClient | ApifyClientAsync) -> None: test_input = {'message': 'Hello from test'} # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task with input - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, task_input=test_input, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Get input - result = await maybe_await(task_client.get_input()) - assert result is not None - retrieved_input = cast('dict', result) + retrieved_input = await maybe_await(task_client.get_input()) + assert isinstance(retrieved_input, dict) assert retrieved_input.get('message') == 'Hello from test' # Update input new_input = {'message': 'Updated message'} - result = await maybe_await(task_client.update_input(task_input=new_input)) - assert result is not None - updated_input = cast('dict', result) + updated_input = await maybe_await(task_client.update_input(task_input=new_input)) + assert isinstance(updated_input, dict) assert updated_input.get('message') == 'Updated message' finally: await maybe_await(task_client.delete()) @@ -168,32 +157,29 @@ async def test_task_start(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Start the task - result = await maybe_await(task_client.start()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(task_client.start()) + assert isinstance(run, Run) assert run.id is not None assert run.act_id == actor.id # Wait for the run to finish - result = await maybe_await(client.run(run.id).wait_for_finish()) - finished_run = cast('Run', result) - assert finished_run is not None + finished_run = await maybe_await(client.run(run.id).wait_for_finish()) + assert isinstance(finished_run, Run) assert finished_run.status == 'SUCCEEDED' # Cleanup run @@ -207,25 +193,23 @@ async def test_task_call(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Call the task (waits for finish) - result = await maybe_await(task_client.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(task_client.call()) + assert isinstance(run, Run) assert run.id is not None assert run.status == 'SUCCEEDED' @@ -240,18 +224,17 @@ async def test_task_delete(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) # Delete task @@ -267,31 +250,28 @@ async def test_task_runs(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Run the task - result = await maybe_await(task_client.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(task_client.call()) + assert isinstance(run, Run) # List runs for this task runs_client = task_client.runs() - result = await maybe_await(runs_client.list(limit=10)) - runs_page = cast('ListOfRuns', result) - assert runs_page is not None + runs_page = await maybe_await(runs_client.list(limit=10)) + assert isinstance(runs_page, ListOfRuns) assert runs_page.items is not None assert len(runs_page.items) >= 1 @@ -308,31 +288,28 @@ async def test_task_last_run(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Run the task - result = await maybe_await(task_client.call()) - run = cast('Run', result) - assert run is not None + run = await maybe_await(task_client.call()) + assert isinstance(run, Run) # Get last run client last_run_client = task_client.last_run() - result = await maybe_await(last_run_client.get()) - last_run = cast('Run', result) - assert last_run is not None + last_run = await maybe_await(last_run_client.get()) + assert isinstance(last_run, Run) assert last_run.id == run.id # Cleanup run @@ -348,26 +325,24 @@ async def test_task_webhooks(client: ApifyClient | ApifyClientAsync) -> None: task_name = get_random_resource_name('task') # Get the actor ID for hello-world - result = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) - actor = cast('Actor', result) - assert actor is not None + actor = await maybe_await(client.actor(HELLO_WORLD_ACTOR).get()) + assert isinstance(actor, Actor) # Create task - result = await maybe_await( + created_task = await maybe_await( client.tasks().create( actor_id=actor.id, name=task_name, ) ) - created_task = cast('Task', result) + assert isinstance(created_task, Task) task_client = client.task(created_task.id) try: # Get webhooks client webhooks_client = task_client.webhooks() - result = await maybe_await(webhooks_client.list()) - webhooks_page = cast('ListOfWebhooks', result) - assert webhooks_page is not None + webhooks_page = await maybe_await(webhooks_client.list()) + assert isinstance(webhooks_page, ListOfWebhooks) assert webhooks_page.items is not None # New task should have no webhooks assert len(webhooks_page.items) == 0 diff --git a/tests/integration/test_user.py b/tests/integration/test_user.py index 4b632faf..5abde190 100644 --- a/tests/integration/test_user.py +++ b/tests/integration/test_user.py @@ -2,42 +2,35 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast - -if TYPE_CHECKING: - from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import AccountLimits, MonthlyUsage, UserPrivateInfo, UserPublicInfo - +from typing import TYPE_CHECKING from ._utils import maybe_await +from apify_client._models import AccountLimits, MonthlyUsage, UserPrivateInfo, UserPublicInfo from apify_client.errors import ApifyApiError +if TYPE_CHECKING: + from apify_client import ApifyClient, ApifyClientAsync + async def test_get_user(client: ApifyClient | ApifyClientAsync) -> None: """Test getting user information.""" - result = await maybe_await(client.user().get()) - user = cast('UserPublicInfo | UserPrivateInfo', result) - - assert user is not None + user = await maybe_await(client.user().get()) + assert isinstance(user, UserPublicInfo | UserPrivateInfo) # UserPublicInfo has username but not id assert user.username is not None async def test_limits(client: ApifyClient | ApifyClientAsync) -> None: """Test getting account limits.""" - result = await maybe_await(client.user().limits()) - limits = cast('AccountLimits', result) - + limits = await maybe_await(client.user().limits()) # Verify we have at least some limit information. The actual fields depend on the account type. - assert limits is not None + assert isinstance(limits, AccountLimits) async def test_monthly_usage(client: ApifyClient | ApifyClientAsync) -> None: """Test retrieving monthly usage information.""" - result = await maybe_await(client.user().monthly_usage()) - usage = cast('MonthlyUsage', result) - - assert usage is not None + usage = await maybe_await(client.user().monthly_usage()) + assert isinstance(usage, MonthlyUsage) # Verify expected fields exist assert usage.usage_cycle is not None assert isinstance(usage.monthly_service_usage, dict) @@ -53,9 +46,8 @@ async def test_update_limits(client: ApifyClient | ApifyClientAsync) -> None: user_client = client.user() # Get current limits to see what's available - result = await maybe_await(user_client.limits()) - current_limits = cast('AccountLimits', result) - assert current_limits is not None + current_limits = await maybe_await(user_client.limits()) + assert isinstance(current_limits, AccountLimits) # Try to update data retention days (allowed on most accounts). We try to set it to the current # value or a reasonable default. diff --git a/tests/integration/test_webhook_dispatch.py b/tests/integration/test_webhook_dispatch.py index 81840094..fbfcf5e2 100644 --- a/tests/integration/test_webhook_dispatch.py +++ b/tests/integration/test_webhook_dispatch.py @@ -2,22 +2,19 @@ from __future__ import annotations -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING + +from ._utils import maybe_await +from apify_client._models import ListOfWebhookDispatches, WebhookDispatch if TYPE_CHECKING: from apify_client import ApifyClient, ApifyClientAsync - from apify_client._models import ListOfWebhookDispatches, WebhookDispatch - - -from ._utils import maybe_await async def test_webhook_dispatch_list(client: ApifyClient | ApifyClientAsync) -> None: """Test listing webhook dispatches.""" - result = await maybe_await(client.webhook_dispatches().list(limit=10)) - dispatches_page = cast('ListOfWebhookDispatches', result) - - assert dispatches_page is not None + dispatches_page = await maybe_await(client.webhook_dispatches().list(limit=10)) + assert isinstance(dispatches_page, ListOfWebhookDispatches) assert dispatches_page.items is not None assert isinstance(dispatches_page.items, list) # User may have 0 dispatches, so we just verify the structure @@ -26,17 +23,14 @@ async def test_webhook_dispatch_list(client: ApifyClient | ApifyClientAsync) -> async def test_webhook_dispatch_get(client: ApifyClient | ApifyClientAsync) -> None: """Test getting a specific webhook dispatch.""" # First list dispatches to get a dispatch ID - result = await maybe_await(client.webhook_dispatches().list(limit=1)) - dispatches_page = cast('ListOfWebhookDispatches', result) - assert dispatches_page is not None + dispatches_page = await maybe_await(client.webhook_dispatches().list(limit=1)) + assert isinstance(dispatches_page, ListOfWebhookDispatches) if dispatches_page.items: # If there are dispatches, test the get method dispatch_id = dispatches_page.items[0].id - result = await maybe_await(client.webhook_dispatch(dispatch_id).get()) - dispatch = cast('WebhookDispatch', result) - - assert dispatch is not None + dispatch = await maybe_await(client.webhook_dispatch(dispatch_id).get()) + assert isinstance(dispatch, WebhookDispatch) assert dispatch.id == dispatch_id else: # If no dispatches, test that get returns None for non-existent ID