Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
84 changes: 83 additions & 1 deletion tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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'),
Expand Down
27 changes: 0 additions & 27 deletions tests/integration/test_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 5 additions & 14 deletions tests/integration/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading