Files
shelfmark/tests/e2e/conftest.py
Alex a99dc1501d Prowlarr and IRC sources, Google Books, book series support + more (#361)
## Headline features 

### Prowlarr plugin - search trackers and download usenet/torrent books

- Search any usenet/torrent tracker via Prowlarr, returns books within
Universal search
- Configure download clients in the app settings (Qbittorrent, Deluge,
Transmission, NZBget, SABnzbd)
- Unified download and file handling within the app, same as AA. 

### IRC plugin 
- Search IRCHighway #ebooks channel for books and download right in the
app.
- No setup needed
- Credit to OpenBooks for the broad idea and inspiration for best
practices for ebook-specific search and download.

### Google Books Metadata Provider
- Create a Google Cloud API key and use Google Books as a metadata
provider
- Not the best source (Hardcover is still recommended), but another
option and further redundancy for universal search

### Book series support
  - New "Series" search field in Hardcover provider
  - "Series order" sort option - lists books in reading order
  - "View Series" button in book details modal to search the full series
  - Series info display (e.g., "3 of 12 in The Wheel of Time")

## Others: 

- Better format filtering, helpful errors when formats rejected (e.g.,
"Found 3 ebooks but format not supported (.pdf). Enable in Settings >
Formats."
- Directory processing - Handles multi-file torrent/usenet downloads
properly
- Expand search toggle - Skip ISBN search to find more editions
- Filtered authors - Uses primary authors only (excludes
translators/narrators) for better search results
- Language multi-select - Filter releases by multiple languages

 Docker / Build / Testing

  - pip cache mounts - Faster Docker builds via BuildKit cache
  - npm cache mounts - Faster frontend builds
  - APT cleanup - Smaller final image size
  - Added make restart command for quick restarts without rebuild
- New pytest-based test framework with proper configuration
(pyproject.toml)
- Unit tests for all download clients (qBittorrent, Transmission,
Deluge, NZBGet, SABnzbd)
  - Bencode parsing tests
  - Cache tests
  - Integration tests for Prowlarr handler
  - E2E test framework
2025-12-27 14:59:06 +00:00

173 lines
5.1 KiB
Python

"""
E2E Test Configuration and Fixtures.
These tests require the full application stack to be running.
Run with: docker exec test-cwabd python3 -m pytest tests/e2e/ -v -m e2e
"""
import os
import time
from typing import Generator, List, Optional
from dataclasses import dataclass, field
import pytest
import requests
# Default test configuration
DEFAULT_BASE_URL = "http://localhost:8084"
DEFAULT_TIMEOUT = 10
POLL_INTERVAL = 2
DOWNLOAD_TIMEOUT = 300 # 5 minutes max for downloads
@dataclass
class APIClient:
"""HTTP client for E2E API testing."""
base_url: str
timeout: int = DEFAULT_TIMEOUT
session: requests.Session = field(default_factory=requests.Session)
def get(self, path: str, **kwargs) -> requests.Response:
"""Make a GET request."""
kwargs.setdefault("timeout", self.timeout)
return self.session.get(f"{self.base_url}{path}", **kwargs)
def post(self, path: str, **kwargs) -> requests.Response:
"""Make a POST request."""
kwargs.setdefault("timeout", self.timeout)
return self.session.post(f"{self.base_url}{path}", **kwargs)
def put(self, path: str, **kwargs) -> requests.Response:
"""Make a PUT request."""
kwargs.setdefault("timeout", self.timeout)
return self.session.put(f"{self.base_url}{path}", **kwargs)
def delete(self, path: str, **kwargs) -> requests.Response:
"""Make a DELETE request."""
kwargs.setdefault("timeout", self.timeout)
return self.session.delete(f"{self.base_url}{path}", **kwargs)
def wait_for_health(self, max_wait: int = 30) -> bool:
"""Wait for the server to be healthy."""
start = time.time()
while time.time() - start < max_wait:
try:
resp = self.get("/api/health")
if resp.status_code == 200:
return True
except requests.exceptions.ConnectionError:
pass
time.sleep(1)
return False
@dataclass
class DownloadTracker:
"""Tracks downloads for cleanup after tests."""
client: APIClient
queued_ids: List[str] = field(default_factory=list)
def track(self, book_id: str) -> str:
"""Track a book ID for cleanup."""
self.queued_ids.append(book_id)
return book_id
def cleanup(self) -> None:
"""Cancel all tracked downloads."""
for book_id in self.queued_ids:
try:
self.client.delete(f"/api/download/{book_id}/cancel")
except Exception:
pass # Best effort cleanup
self.queued_ids.clear()
def wait_for_status(
self,
book_id: str,
target_states: List[str],
timeout: int = DOWNLOAD_TIMEOUT,
) -> Optional[dict]:
"""
Poll status until book reaches one of the target states.
Args:
book_id: The book/task ID to check
target_states: List of states to wait for (e.g., ["complete", "error"])
timeout: Maximum seconds to wait
Returns:
Status dict if target state reached, None if timeout
"""
start = time.time()
while time.time() - start < timeout:
try:
resp = self.client.get("/api/status")
if resp.status_code != 200:
time.sleep(POLL_INTERVAL)
continue
status_data = resp.json()
# Check each status category
for state in target_states:
if state in status_data and book_id in status_data[state]:
return {
"state": state,
"data": status_data[state][book_id],
}
# Check for error state
if "error" in status_data and book_id in status_data["error"]:
return {
"state": "error",
"data": status_data["error"][book_id],
}
except Exception:
pass
time.sleep(POLL_INTERVAL)
return None
@pytest.fixture(scope="session")
def base_url() -> str:
"""Get the base URL for the API server."""
return os.environ.get("E2E_BASE_URL", DEFAULT_BASE_URL)
@pytest.fixture(scope="session")
def api_client(base_url: str) -> Generator[APIClient, None, None]:
"""Create an API client for the test session."""
client = APIClient(base_url=base_url)
# Wait for server to be healthy
if not client.wait_for_health():
pytest.skip("Server not available - ensure the app is running")
yield client
# Cleanup session
client.session.close()
@pytest.fixture
def download_tracker(api_client: APIClient) -> Generator[DownloadTracker, None, None]:
"""Create a download tracker that cleans up after each test."""
tracker = DownloadTracker(client=api_client)
yield tracker
tracker.cleanup()
@pytest.fixture(scope="session")
def server_config(api_client: APIClient) -> dict:
"""Get server configuration."""
resp = api_client.get("/api/config")
if resp.status_code != 200:
return {}
return resp.json()