From 59cfabf1cd337a514a4d7a8eb4f1873009a8ff9b Mon Sep 17 00:00:00 2001 From: yashvanzara Date: Sat, 12 Sep 2026 17:26:50 +0100 Subject: [PATCH] feat: add Docker Compose integration tests Spin up a pinned Readeck container, create a test user and API token, and exercise live bookmark, export, profile, and public OAuth APIs with cleanup-first fixtures. Default pytest still runs unit tests only. --- .github/workflows/ci.yml | 28 ++++ CHANGELOG.md | 13 ++ README.md | 3 + pyproject.toml | 3 + src/readeck/__init__.py | 2 +- src/readeck/models.py | 4 +- tests/conftest.py | 27 ++++ tests/integration/__init__.py | 1 + tests/integration/compose.yaml | 20 +++ tests/integration/conftest.py | 124 +++++++++++++++ tests/integration/helpers.py | 205 +++++++++++++++++++++++++ tests/integration/test_bookmarks.py | 91 +++++++++++ tests/integration/test_errors.py | 29 ++++ tests/integration/test_export.py | 38 +++++ tests/integration/test_health.py | 23 +++ tests/integration/test_highlights.py | 16 ++ tests/integration/test_oauth_public.py | 38 +++++ tests/integration/waiters.py | 31 ++++ tests/test_models.py | 5 + 19 files changed, 699 insertions(+), 2 deletions(-) create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/compose.yaml create mode 100644 tests/integration/conftest.py create mode 100644 tests/integration/helpers.py create mode 100644 tests/integration/test_bookmarks.py create mode 100644 tests/integration/test_errors.py create mode 100644 tests/integration/test_export.py create mode 100644 tests/integration/test_health.py create mode 100644 tests/integration/test_highlights.py create mode 100644 tests/integration/test_oauth_public.py create mode 100644 tests/integration/waiters.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83487fa..324091b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,6 +50,34 @@ jobs: flags: unittests name: codecov-umbrella + integration: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v3 + with: + version: "latest" + + - name: Set up Python 3.12 + run: uv python install 3.12 + + - name: Install dependencies + run: uv sync --dev + + - name: Pull Readeck image + run: docker compose -p readeck-python-itest -f tests/integration/compose.yaml pull + + - name: Run integration tests + run: uv run pytest tests/integration -v + + - name: Tear down leftover Compose stack + if: always() + run: | + docker compose -p readeck-python-itest -f tests/integration/compose.yaml down -v --remove-orphans --timeout 10 || true + build: runs-on: ubuntu-latest needs: test diff --git a/CHANGELOG.md b/CHANGELOG.md index a3caf05..11c155e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.3.1] - 2026-09-12 + +### Added +- Docker Compose integration tests against a live Readeck instance. + +### Changed +- Default `pytest` runs skip integration tests unless they are selected + explicitly with `-m integration` or by targeting `tests/integration`. +- Integration-only pytest runs disable coverage so the 80% unit-test gate + does not fail a live Docker session. +- Accept user profiles that omit `reader_settings`, matching live Readeck + responses for newly created users. + ## [0.3.0] - 2026-09-12 ### Added diff --git a/README.md b/README.md index ab19010..ca53b74 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,9 @@ uv sync --dev # Run tests uv run pytest +# Run integration tests (requires Docker) +uv run pytest tests/integration + # Run linting and formatting uv run ruff check src tests --fix uv run ruff format src tests diff --git a/pyproject.toml b/pyproject.toml index 570542b..9274519 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -106,6 +106,9 @@ python_classes = ["Test*"] python_functions = ["test_*"] asyncio_default_fixture_loop_scope = "function" asyncio_mode = "auto" +markers = [ + "integration: live Readeck tests via Docker Compose", +] addopts = [ "--cov=src/readeck", "--cov-report=term-missing", diff --git a/src/readeck/__init__.py b/src/readeck/__init__.py index a830df1..aeeb2f3 100644 --- a/src/readeck/__init__.py +++ b/src/readeck/__init__.py @@ -4,7 +4,7 @@ Readeck's bookmark and reading features. """ -__version__ = "0.3.0" +__version__ = "0.3.1" __author__ = "Yash Vanzara" __email__ = "yashvanzara@gmail.com" diff --git a/src/readeck/models.py b/src/readeck/models.py index cf697da..ab5f69f 100644 --- a/src/readeck/models.py +++ b/src/readeck/models.py @@ -35,7 +35,9 @@ class UserSettings(BaseModel): """User settings and preferences.""" debug_info: bool = Field(..., description="Enable debug information") - reader_settings: ReaderSettings = Field(..., description="Reader configuration") + reader_settings: ReaderSettings | None = Field( + default=None, description="Reader configuration" + ) lang: str = Field(default="en-US", description="Language setting") addon_reminder: bool = Field(default=True, description="Show addon reminders") email_settings: EmailSettings = Field( diff --git a/tests/conftest.py b/tests/conftest.py index 2c92a52..02beed8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ """Test fixtures and utilities.""" from collections.abc import AsyncGenerator +from pathlib import Path from typing import Any import pytest @@ -8,6 +9,32 @@ from readeck import ReadeckClient +def pytest_configure(config: pytest.Config) -> None: + """Do not apply the unit-test coverage gate to live integration runs.""" + markexpr = (config.option.markexpr or "").strip() + args = [str(arg) for arg in config.args] + integration_only = "integration" in markexpr or ( + bool(args) and all("integration" in arg for arg in args) + ) + if not integration_only: + return + cov = config.pluginmanager.getplugin("_cov") + if cov is not None: + config.pluginmanager.unregister(cov) + + +def pytest_ignore_collect(collection_path: Path, config: pytest.Config) -> bool | None: + """Skip the live Docker suite unless it was requested explicitly.""" + if "integration" not in Path(collection_path).parts: + return None + markexpr = (config.option.markexpr or "").strip() + if "integration" in markexpr: + return False + if any("integration" in str(arg) for arg in config.args): + return False + return True + + @pytest.fixture def mock_user_profile_data() -> dict[str, Any]: """Mock user profile response data.""" diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..91fd780 --- /dev/null +++ b/tests/integration/__init__.py @@ -0,0 +1 @@ +"""Live integration tests against a Dockerized Readeck instance.""" diff --git a/tests/integration/compose.yaml b/tests/integration/compose.yaml new file mode 100644 index 0000000..b7c46b6 --- /dev/null +++ b/tests/integration/compose.yaml @@ -0,0 +1,20 @@ +services: + app: + image: codeberg.org/readeck/readeck:0.23.2 + ports: + - "18765:8000" + environment: + READECK_LOG_LEVEL: info + READECK_SERVER_HOST: "0.0.0.0" + READECK_SERVER_PORT: 8000 + READECK_LOG_FORMAT: text + volumes: + - ${READECK_ITEST_DATA:-/tmp/readeck-python-itest}:/readeck + security_opt: + - no-new-privileges + healthcheck: + test: ["CMD", "/bin/readeck", "healthcheck", "-config", "config.toml"] + interval: 2s + timeout: 2s + retries: 30 + start_period: 10s diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 0000000..f7ab937 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,124 @@ +"""Session fixtures for Dockerized Readeck integration tests.""" + +from __future__ import annotations + +import atexit +import tempfile +from collections.abc import AsyncGenerator, Generator +from pathlib import Path + +import pytest + +from readeck import ReadeckClient, ReadeckError, ReadeckOAuthClient + +from .helpers import ( + BASE_URL, + COMPOSE_FILE, + TEST_PASSWORD, + TEST_USERNAME, + ReadeckCredentials, + ReadeckStack, + compose, + compose_down, + create_api_token, + create_test_user, + docker_available, + remove_data_dir, + wait_for_http, +) + +_ACTIVE_DATA_DIR: Path | None = None + + +def _atexit_teardown() -> None: + if _ACTIVE_DATA_DIR is None: + return + compose_down(_ACTIVE_DATA_DIR) + remove_data_dir(_ACTIVE_DATA_DIR) + + +atexit.register(_atexit_teardown) + + +@pytest.fixture(scope="session") +def readeck_stack() -> Generator[ReadeckStack, None, None]: + """Start Readeck, always tearing down leftover or current Compose state.""" + global _ACTIVE_DATA_DIR + + if not docker_available(): + pytest.skip("Docker daemon is not available") + if not COMPOSE_FILE.exists(): + pytest.fail(f"Compose file is missing: {COMPOSE_FILE}") + + data_dir = Path(tempfile.mkdtemp(prefix="readeck-python-itest-")) + data_dir.mkdir(parents=True, exist_ok=True) + _ACTIVE_DATA_DIR = data_dir + + compose_down(data_dir) + try: + started = compose( + ["up", "-d", "--wait", "--wait-timeout", "120"], + data_dir, + timeout=240, + ) + if started.returncode != 0: + logs = compose(["logs"], data_dir, timeout=30) + pytest.fail( + "Failed to start Readeck Compose stack.\n" + f"stdout:\n{started.stdout}\nstderr:\n{started.stderr}\n" + f"logs:\n{logs.stdout}\n{logs.stderr}" + ) + wait_for_http(BASE_URL) + yield ReadeckStack(base_url=BASE_URL, data_dir=data_dir) + finally: + compose_down(data_dir) + remove_data_dir(data_dir) + _ACTIVE_DATA_DIR = None + + +@pytest.fixture(scope="session") +def readeck_credentials(readeck_stack: ReadeckStack) -> ReadeckCredentials: + """Create the test user and an API token against the live instance.""" + create_test_user(readeck_stack.data_dir) + token = create_api_token(readeck_stack.base_url, TEST_USERNAME, TEST_PASSWORD) + return ReadeckCredentials( + base_url=readeck_stack.base_url, + token=token, + username=TEST_USERNAME, + password=TEST_PASSWORD, + ) + + +@pytest.fixture +async def readeck_client( + readeck_credentials: ReadeckCredentials, +) -> AsyncGenerator[ReadeckClient, None]: + """Authenticated client closed after each test.""" + async with ReadeckClient( + base_url=readeck_credentials.base_url, + token=readeck_credentials.token, + ) as client: + yield client + + +@pytest.fixture +async def readeck_oauth_client( + readeck_stack: ReadeckStack, +) -> AsyncGenerator[ReadeckOAuthClient, None]: + """Unauthenticated OAuth client closed after each test.""" + async with ReadeckOAuthClient(base_url=readeck_stack.base_url) as client: + yield client + + +@pytest.fixture +async def created_bookmarks( + readeck_client: ReadeckClient, +) -> AsyncGenerator[list[str], None]: + """Track bookmark IDs created during a test and delete them afterwards.""" + bookmark_ids: list[str] = [] + yield bookmark_ids + for bookmark_id in bookmark_ids: + try: + await readeck_client.delete_bookmark(bookmark_id) + except ReadeckError: + pass diff --git a/tests/integration/helpers.py b/tests/integration/helpers.py new file mode 100644 index 0000000..2168313 --- /dev/null +++ b/tests/integration/helpers.py @@ -0,0 +1,205 @@ +"""Helpers for Docker Compose integration tests.""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import time +from dataclasses import dataclass +from pathlib import Path + +import httpx + +COMPOSE_FILE = Path(__file__).parent / "compose.yaml" +COMPOSE_PROJECT = "readeck-python-itest" +BASE_URL = "http://127.0.0.1:18765" +TEST_USERNAME = "itest" +TEST_PASSWORD = "ItestPass123!" +TEST_EMAIL = "itest@example.com" + +BEARER_TOKEN = re.compile(r"Authorization:\s*Bearer\s+([A-Za-z0-9]+)") +CLIPBOARD_VALUE = re.compile( + r'data-clipboard-target="content"\s+value="([^"]+)"', + re.I, +) + + +@dataclass(frozen=True) +class ReadeckStack: + """Running Readeck Compose stack.""" + + base_url: str + data_dir: Path + + +@dataclass(frozen=True) +class ReadeckCredentials: + """API credentials for the integration-test user.""" + + base_url: str + token: str + username: str + password: str + + +def docker_available() -> bool: + """Return True when the Docker daemon responds.""" + try: + result = subprocess.run( + ["docker", "info"], + capture_output=True, + timeout=10, + check=False, + ) + except (OSError, subprocess.TimeoutExpired): + return False + return result.returncode == 0 + + +def compose_env(data_dir: Path) -> dict[str, str]: + """Build an environment with the Compose data-directory override.""" + env = os.environ.copy() + env["READECK_ITEST_DATA"] = str(data_dir) + return env + + +def compose( + args: list[str], + data_dir: Path, + timeout: int = 120, +) -> subprocess.CompletedProcess[str]: + """Run a docker compose command for the integration-test project.""" + return subprocess.run( + [ + "docker", + "compose", + "-p", + COMPOSE_PROJECT, + "-f", + str(COMPOSE_FILE), + *args, + ], + env=compose_env(data_dir), + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + + +def compose_down(data_dir: Path) -> None: + """Stop the stack and remove containers, networks, and volumes.""" + compose( + ["down", "-v", "--remove-orphans", "--timeout", "10"], + data_dir, + timeout=60, + ) + + +def wait_for_http(base_url: str, timeout: float = 60.0) -> None: + """Wait until the Readeck HTTP server accepts connections.""" + deadline = time.monotonic() + timeout + last_error = "timeout" + while time.monotonic() < deadline: + try: + response = httpx.get(base_url, follow_redirects=True, timeout=2.0) + if response.status_code < 500: + return + last_error = f"HTTP {response.status_code}" + except httpx.HTTPError as exc: + last_error = str(exc) + time.sleep(1) + raise RuntimeError(f"Readeck did not become reachable at {base_url}: {last_error}") + + +def create_test_user(data_dir: Path) -> None: + """Create or update the integration-test user via the Readeck CLI.""" + last = None + for _ in range(10): + last = compose( + [ + "exec", + "-T", + "app", + "/bin/readeck", + "user", + "-config", + "config.toml", + "-u", + TEST_USERNAME, + "-p", + TEST_PASSWORD, + "-email", + TEST_EMAIL, + "-group", + "admin", + ], + data_dir, + timeout=30, + ) + if last.returncode == 0: + return + time.sleep(2) + detail = "" + if last is not None: + detail = f"\nstdout:\n{last.stdout}\nstderr:\n{last.stderr}" + raise RuntimeError(f"Failed to create Readeck test user.{detail}") + + +def _extract_api_token(html: str) -> str | None: + match = BEARER_TOKEN.search(html) + if match: + return match.group(1) + for match in CLIPBOARD_VALUE.finditer(html): + value = match.group(1).strip() + if value.startswith("Authorization:"): + bearer = BEARER_TOKEN.search(value) + if bearer: + return bearer.group(1) + continue + if value: + return value + return None + + +def create_api_token(base_url: str, username: str, password: str) -> str: + """Log in via the HTML form and create a Bearer token for API tests. + + Readeck's OpenAPI docs (``/docs/api``) describe script auth as: generate a + token from ``/profile/tokens`` and send it as ``Authorization: Bearer``. + There is no JSON login route that returns a token. + """ + with httpx.Client(base_url=base_url, follow_redirects=True, timeout=30.0) as client: + login = client.post( + "/login", + data={"username": username, "password": password, "r": ""}, + ) + if login.status_code >= 400: + raise RuntimeError( + f"Readeck login failed: HTTP {login.status_code}: {login.text[:300]}" + ) + + profile = client.get("/api/profile", headers={"Accept": "application/json"}) + if profile.status_code != 200: + raise RuntimeError( + "Readeck login did not establish a session: " + f"HTTP {profile.status_code}: {profile.text[:300]}" + ) + + created = client.post("/profile/tokens") + if created.status_code >= 400: + raise RuntimeError( + "Readeck token creation failed: " + f"HTTP {created.status_code}: {created.text[:300]}" + ) + token = _extract_api_token(created.text) + if not token: + raise RuntimeError("Readeck token page did not include an API token") + return token + + +def remove_data_dir(data_dir: Path) -> None: + """Delete the temporary Compose data directory.""" + shutil.rmtree(data_dir, ignore_errors=True) diff --git a/tests/integration/test_bookmarks.py b/tests/integration/test_bookmarks.py new file mode 100644 index 0000000..d725193 --- /dev/null +++ b/tests/integration/test_bookmarks.py @@ -0,0 +1,91 @@ +"""Live bookmark create, list, update, label, and delete tests.""" + +import pytest + +from readeck import BookmarkListParams, BookmarkUpdateRequest, ReadeckClient +from readeck.exceptions import ReadeckNotFoundError + +from .waiters import wait_until_loaded + +pytestmark = pytest.mark.integration + +EXAMPLE_URL = "https://example.com" +EXAMPLE_ORG_URL = "https://example.org" + + +@pytest.mark.asyncio +async def test_create_get_list_and_delete_bookmark( + readeck_client: ReadeckClient, created_bookmarks: list[str] +) -> None: + created = await readeck_client.create_bookmark( + url=EXAMPLE_URL, + title="Example Article", + labels=["itest", "docs"], + ) + assert created.bookmark_id + created_bookmarks.append(created.bookmark_id) + + bookmark = await wait_until_loaded(readeck_client, created.bookmark_id) + assert bookmark.id == created.bookmark_id + assert EXAMPLE_URL in bookmark.url or bookmark.href.endswith("example.com/") + assert "itest" in bookmark.labels + + listed = await readeck_client.get_bookmarks(BookmarkListParams(limit=50)) + assert any(item.id == created.bookmark_id for item in listed) + + searched = await readeck_client.get_bookmarks( + BookmarkListParams(search="example", limit=50) + ) + assert any(item.id == created.bookmark_id for item in searched) + + labeled = await readeck_client.get_bookmarks( + BookmarkListParams(labels="itest", limit=50) + ) + assert any(item.id == created.bookmark_id for item in labeled) + + await readeck_client.delete_bookmark(created.bookmark_id) + created_bookmarks.remove(created.bookmark_id) + with pytest.raises(ReadeckNotFoundError): + await readeck_client.get_bookmark(created.bookmark_id) + + +@pytest.mark.asyncio +async def test_update_bookmark_and_labels( + readeck_client: ReadeckClient, created_bookmarks: list[str] +) -> None: + created = await readeck_client.create_bookmark( + url=EXAMPLE_ORG_URL, + title="Original Title", + labels=["keep"], + ) + assert created.bookmark_id + created_bookmarks.append(created.bookmark_id) + await wait_until_loaded(readeck_client, created.bookmark_id) + + updated = await readeck_client.update_bookmark( + created.bookmark_id, + BookmarkUpdateRequest( + title="Updated Title", + is_marked=True, + add_labels=["added"], + ), + ) + assert created.bookmark_id in updated.href + + bookmark = await readeck_client.get_bookmark(created.bookmark_id) + assert bookmark.title == "Updated Title" + assert bookmark.is_marked is True + assert "keep" in bookmark.labels + assert "added" in bookmark.labels + + await readeck_client.update_bookmark( + created.bookmark_id, + BookmarkUpdateRequest(remove_labels=["added"]), + ) + bookmark = await readeck_client.get_bookmark(created.bookmark_id) + assert "added" not in bookmark.labels + assert "keep" in bookmark.labels + + labels = await readeck_client.get_labels() + names = {label.name for label in labels} + assert "keep" in names diff --git a/tests/integration/test_errors.py b/tests/integration/test_errors.py new file mode 100644 index 0000000..569e5bf --- /dev/null +++ b/tests/integration/test_errors.py @@ -0,0 +1,29 @@ +"""Live error-path coverage.""" + +import pytest + +from readeck import ReadeckClient +from readeck.exceptions import ReadeckAuthError, ReadeckNotFoundError + +from .helpers import ReadeckCredentials + +pytestmark = pytest.mark.integration + + +@pytest.mark.asyncio +async def test_invalid_token_raises_auth_error( + readeck_credentials: ReadeckCredentials, +) -> None: + async with ReadeckClient( + base_url=readeck_credentials.base_url, token="not-a-real-token" + ) as client: + with pytest.raises(ReadeckAuthError): + await client.get_user_profile() + + +@pytest.mark.asyncio +async def test_missing_bookmark_raises_not_found( + readeck_client: ReadeckClient, +) -> None: + with pytest.raises(ReadeckNotFoundError): + await readeck_client.get_bookmark("does-not-exist") diff --git a/tests/integration/test_export.py b/tests/integration/test_export.py new file mode 100644 index 0000000..f20d8f5 --- /dev/null +++ b/tests/integration/test_export.py @@ -0,0 +1,38 @@ +"""Live bookmark export tests.""" + +import pytest + +from readeck import ReadeckClient + +from .waiters import wait_until_loaded + +pytestmark = pytest.mark.integration + + +@pytest.mark.asyncio +async def test_export_markdown_and_epub( + readeck_client: ReadeckClient, created_bookmarks: list[str] +) -> None: + created = await readeck_client.create_bookmark( + url="https://example.com", + title="Export Target", + labels=["export"], + ) + assert created.bookmark_id + created_bookmarks.append(created.bookmark_id) + bookmark = await wait_until_loaded(readeck_client, created.bookmark_id) + + if not bookmark.loaded and not bookmark.has_article: + pytest.skip("Readeck did not finish extracting the bookmark") + + markdown = await readeck_client.export_bookmark(created.bookmark_id, format="md") + assert isinstance(markdown, str) + assert markdown.strip() + + parsed = await readeck_client.export_bookmark_parsed(created.bookmark_id) + assert parsed.raw_content.strip() + assert parsed.content is not None + + epub = await readeck_client.export_bookmark(created.bookmark_id, format="epub") + assert isinstance(epub, bytes) + assert len(epub) > 0 diff --git a/tests/integration/test_health.py b/tests/integration/test_health.py new file mode 100644 index 0000000..e350e37 --- /dev/null +++ b/tests/integration/test_health.py @@ -0,0 +1,23 @@ +"""Live health and profile checks.""" + +import pytest + +from readeck import ReadeckClient + +from .helpers import ReadeckCredentials + +pytestmark = pytest.mark.integration + + +@pytest.mark.asyncio +async def test_health_check(readeck_client: ReadeckClient) -> None: + assert await readeck_client.health_check() is True + + +@pytest.mark.asyncio +async def test_get_user_profile( + readeck_client: ReadeckClient, readeck_credentials: ReadeckCredentials +) -> None: + profile = await readeck_client.get_user_profile() + assert profile.user.username == readeck_credentials.username + assert profile.user.email == "itest@example.com" diff --git a/tests/integration/test_highlights.py b/tests/integration/test_highlights.py new file mode 100644 index 0000000..46d5694 --- /dev/null +++ b/tests/integration/test_highlights.py @@ -0,0 +1,16 @@ +"""Live highlights listing.""" + +import pytest + +from readeck import HighlightListResponse, ReadeckClient + +pytestmark = pytest.mark.integration + + +@pytest.mark.asyncio +async def test_get_highlights(readeck_client: ReadeckClient) -> None: + result = await readeck_client.get_highlights(limit=10) + assert isinstance(result, HighlightListResponse) + assert result.total_count >= 0 + assert result.page >= 1 + assert isinstance(result.items, list) diff --git a/tests/integration/test_oauth_public.py b/tests/integration/test_oauth_public.py new file mode 100644 index 0000000..b523bf3 --- /dev/null +++ b/tests/integration/test_oauth_public.py @@ -0,0 +1,38 @@ +"""Live public OAuth discovery and client registration.""" + +import pytest + +from readeck import OAuthClientRegistrationRequest, ReadeckOAuthClient + +pytestmark = pytest.mark.integration + + +@pytest.mark.asyncio +async def test_info_and_server_metadata( + readeck_oauth_client: ReadeckOAuthClient, +) -> None: + info = await readeck_oauth_client.get_info() + assert info.version.canonical + if not info.supports_oauth: + pytest.skip("Readeck instance does not advertise OAuth") + + metadata = await readeck_oauth_client.get_server_metadata() + assert str(metadata.token_endpoint).endswith("/api/oauth/token") + + +@pytest.mark.asyncio +async def test_register_public_client(readeck_oauth_client: ReadeckOAuthClient) -> None: + info = await readeck_oauth_client.get_info() + if not info.supports_oauth: + pytest.skip("Readeck instance does not advertise OAuth") + + registration = await readeck_oauth_client.register_client( + OAuthClientRegistrationRequest( + client_name="readeck-python-itest", + client_uri="https://example.com", + software_id="io.github.yashvanzara.readeck-python", + software_version="0.3.1", + ) + ) + assert registration.client_id + assert registration.client_name == "readeck-python-itest" diff --git a/tests/integration/waiters.py b/tests/integration/waiters.py new file mode 100644 index 0000000..a394456 --- /dev/null +++ b/tests/integration/waiters.py @@ -0,0 +1,31 @@ +"""Polling helpers for asynchronous Readeck operations.""" + +from __future__ import annotations + +import asyncio + +from readeck import Bookmark, ReadeckClient, ReadeckError + + +async def wait_until_loaded( + client: ReadeckClient, + bookmark_id: str, + timeout: float = 30.0, +) -> Bookmark: + """Poll until a bookmark reports that content extraction finished.""" + deadline = asyncio.get_running_loop().time() + timeout + last_error: Exception | None = None + bookmark: Bookmark | None = None + while asyncio.get_running_loop().time() < deadline: + try: + bookmark = await client.get_bookmark(bookmark_id) + if bookmark.loaded or bookmark.has_article: + return bookmark + except ReadeckError as exc: + last_error = exc + await asyncio.sleep(1) + if bookmark is not None: + return bookmark + raise AssertionError( + f"Bookmark {bookmark_id} was not available before timeout: {last_error}" + ) diff --git a/tests/test_models.py b/tests/test_models.py index 7d77f68..5ff8ff6 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -96,6 +96,11 @@ def test_nested_reader_settings(self): assert settings.reader_settings.font == "Helvetica" assert settings.reader_settings.font_size == 14 + def test_user_settings_without_reader_settings(self): + """Live Readeck may omit reader settings for a newly created user.""" + settings = UserSettings(debug_info=False) + assert settings.reader_settings is None + class TestUser: """Test User model."""