diff --git a/pyproject.toml b/pyproject.toml index e8cfe5912..34d775918 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,6 +56,7 @@ dev = [ # We explicitly constrain black>=24.3.0 to override the transitive dependency. "black>=24.3.0", "datamodel-code-generator[http,ruff]>=0.85.0,<1.0.0", + "filelock<5.0.0", "griffe<3.0.0", "poethepoet<1.0.0", "pre-commit<5.0.0", diff --git a/tests/README.md b/tests/README.md index 4f8c9d15a..90be860b8 100644 --- a/tests/README.md +++ b/tests/README.md @@ -63,6 +63,7 @@ To run them against a different Apify API environment, also set `APIFY_INTEGRATI - `client`: an `ApifyClient` or `ApifyClientAsync` for the main test user. Each test that uses it runs four times, once for each combination of sync or async client and `impit` or `httpx2` transport. - `client_with_request_body_compressor`: a sync client with the `impit` transport, run once per built-in request-body compressor (gzip, brotli, and zstd). `request_body_compressor` gives the compressor of the current run, with its `compress` method wrapped in a `Mock`. - `is_async`: `True` when the test runs with the async client. +- `build_id_of_own_actor`: the ID of a finished build of an Actor owned by the main test user. The API serves a build log only to a user who can write to or build the Actor, so a test that reads a build log uses this build, not a build of a public Actor. The Actor is built once per test run and shared by all xdist workers. - `test_dataset_of_another_user` and `test_kvs_of_another_user`: a dataset and a key-value store owned by the second user, with known content and the signatures for accessing it. ### Writing integration tests diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 73ae46d42..306931cbd 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -2,10 +2,11 @@ import json import os -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from unittest.mock import Mock import pytest +from filelock import FileLock from .._utils import ( TOKEN_ENV_VAR, @@ -16,6 +17,7 @@ KvsFixture, get_api_url, get_crypto_random_object_id, + get_random_resource_name, open_apify_client, ) from apify_client import ApifyClient, ApifyClientAsync @@ -114,6 +116,86 @@ def test_kvs_of_another_user(api_token_2: str) -> Generator[KvsFixture]: kvs_client.delete() +def _create_actor_with_finished_build(client: ApifyClient) -> tuple[str, str]: + """Create an Actor owned by the user of `client`, build it, and return the Actor ID and the finished build ID.""" + actor = client.actors().create( + name=get_random_resource_name('actor'), + versions=[ + { + 'versionNumber': '0.1', + 'sourceType': 'SOURCE_FILES', + 'buildTag': 'latest', + 'sourceFiles': [ + { + 'name': 'main.js', + 'format': 'TEXT', + 'content': 'console.log("Hello")', + } + ], + } + ], + ) + actor_client = client.actor(actor.id) + + try: + build = actor_client.build(version_number='0.1') + finished_build = client.build(build.id).wait_for_finish() + assert finished_build is not None + assert finished_build.status in ('SUCCEEDED', 'FAILED') + except BaseException: + actor_client.delete() + raise + + return actor.id, build.id + + +@pytest.fixture(scope='session') +def build_id_of_own_actor( + api_token: str, + tmp_path_factory: pytest.TempPathFactory, + worker_id: str, +) -> Generator[str]: + """ID of a finished build of an Actor owned by the primary test user, built once per test run. + + The API serves a build log only to a user who can write to or build the Actor, so the builds of a public Actor + such as `apify/hello-world` have no log the test user can read. + + A session-scoped fixture runs once in every xdist worker that needs it. The workers share one Actor through a + state file guarded by a file lock: the first worker builds the Actor, the others reuse the build, and the last + worker to finish deletes the Actor. + """ + api_url = get_api_url() + client = ApifyClient(api_token, api_url=api_url) + + shared_dir = tmp_path_factory.getbasetemp() + if worker_id != 'master': + # The base temporary directory of an xdist worker is a subdirectory of the one of the whole test run. + shared_dir = shared_dir.parent + state_path = shared_dir / 'build_of_own_actor.json' + state_lock = FileLock(f'{state_path}.lock') + + with state_lock: + state: dict[str, Any] + if state_path.is_file(): + state = json.loads(state_path.read_text()) + else: + actor_id, build_id = _create_actor_with_finished_build(client) + state = {'actor_id': actor_id, 'build_id': build_id, 'worker_count': 0} + state['worker_count'] += 1 + state_path.write_text(json.dumps(state)) + + yield state['build_id'] + + with state_lock: + state = json.loads(state_path.read_text()) + state['worker_count'] -= 1 + if state['worker_count'] == 0: + state_path.unlink() + client.actor(state['actor_id']).delete() + else: + state_path.write_text(json.dumps(state)) + + @pytest.fixture( params=[ pytest.param(HttpClientClasses(sync=ImpitHttpClient, async_=ImpitHttpClientAsync), id='impit'), diff --git a/tests/integration/test_build.py b/tests/integration/test_build.py index 648ffeea3..30a2d46c1 100644 --- a/tests/integration/test_build.py +++ b/tests/integration/test_build.py @@ -86,33 +86,6 @@ async def test_user_builds_list(client: ApifyClient | ApifyClientAsync) -> None: assert isinstance(builds_page.items, list) -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) - 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) - completed_build = None - for build in builds_page.items: - if build.status and build.status == 'SUCCEEDED': - completed_build = build - break - - if completed_build is None: - # If no succeeded build found, use any build - completed_build = builds_page.items[0] - - # Get the build log - log_client = client.build(completed_build.id).log() - log_content = await maybe_await(log_client.get()) - - # Build logs should be available for completed builds - assert log_content is not None - - async def test_build_wait_for_finish(client: ApifyClient | ApifyClientAsync) -> None: """Test wait_for_finish on an already completed build.""" # First list builds to get a completed build ID diff --git a/tests/integration/test_log.py b/tests/integration/test_log.py index 150292af4..bf6799e06 100644 --- a/tests/integration/test_log.py +++ b/tests/integration/test_log.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING from .._utils import maybe_await -from apify_client._models import ListOfBuilds, Run +from apify_client._models import Run from apify_client._resource_clients import RunClient, RunClientAsync from apify_client.http_clients import HttpResponse @@ -43,22 +43,13 @@ async def test_log_get_from_run(client: ApifyClient | ApifyClientAsync) -> None: await maybe_await(run_client.delete()) -async def test_log_get_from_build(client: ApifyClient | ApifyClientAsync) -> None: +async def test_log_get_from_build(client: ApifyClient | ApifyClientAsync, build_id_of_own_actor: str) -> None: """Test retrieving log from a build.""" - # Get a build from hello-world actor - actor = client.actor(HELLO_WORLD_ACTOR) - 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 log from the build - build = client.build(build_id) + build = client.build(build_id_of_own_actor) log = await maybe_await(build.log().get()) - # Build log may be None or empty for some builds - if log is not None: - assert isinstance(log, str) + assert isinstance(log, str) + assert len(log) > 0 async def test_log_get_as_bytes(client: ApifyClient | ApifyClientAsync) -> None: diff --git a/uv.lock b/uv.lock index c44293fed..433cd032a 100644 --- a/uv.lock +++ b/uv.lock @@ -71,6 +71,7 @@ zstd = [ dev = [ { name = "black" }, { name = "datamodel-code-generator", extra = ["http", "ruff"] }, + { name = "filelock" }, { name = "griffe" }, { name = "poethepoet" }, { name = "pre-commit" }, @@ -105,6 +106,7 @@ provides-extras = ["brotli", "httpx2", "zstd"] dev = [ { name = "black", specifier = ">=24.3.0" }, { name = "datamodel-code-generator", extras = ["http", "ruff"], specifier = ">=0.85.0,<1.0.0" }, + { name = "filelock", specifier = "<5.0.0" }, { name = "griffe", specifier = "<3.0.0" }, { name = "poethepoet", specifier = "<1.0.0" }, { name = "pre-commit", specifier = "<5.0.0" },