"""Тесты handler-а PEK Scraper. async_playwright целиком замокан — реальный chromium не запускается. Цель — проверить контракт HTTP-эндпоинта (auth, валидация, парсинг ответа, обработка ошибок), а не сам скрапинг. """ from __future__ import annotations import sys from pathlib import Path from types import SimpleNamespace import pytest from fastapi.testclient import TestClient sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import app as scraper_app # noqa: E402 VALID_SELECTORS = { "from_city": 'input[name="from_city"]', "to_city": 'input[name="to_city"]', "weight": 'input[name="weight"]', "volume": 'input[name="volume"]', "places": 'input[name="places"]', "submit": 'button[type="submit"]', "result_price": ".result-price", "result_days": ".result-days", } VALID_BODY = { "city": "Москва", "weight_kg": "250.00", "volume_m3": "1.240", "places_count": 5, "selectors": VALID_SELECTORS, } @pytest.fixture def client(monkeypatch: pytest.MonkeyPatch) -> TestClient: monkeypatch.setenv("PEK_SCRAPER_TOKEN", "secret-test") return TestClient(scraper_app.app) class _FakePage: def __init__(self, price_text: str, days_text: str) -> None: self._price = price_text self._days = days_text self.calls: list[tuple[str, ...]] = [] def set_default_timeout(self, _ms: int) -> None: ... async def goto(self, url: str) -> None: self.calls.append(("goto", url)) async def fill(self, selector: str, value: str) -> None: self.calls.append(("fill", selector, value)) async def click(self, selector: str) -> None: self.calls.append(("click", selector)) async def wait_for_selector(self, _selector: str, timeout: int = 0) -> None: ... async def text_content(self, selector: str) -> str: if selector.endswith("price"): return self._price return self._days class _FakeBrowser: def __init__(self, page: _FakePage) -> None: self._page = page async def new_page(self) -> _FakePage: return self._page async def close(self) -> None: ... class _FakeChromium: def __init__(self, page: _FakePage) -> None: self._page = page async def launch(self, headless: bool = True) -> _FakeBrowser: return _FakeBrowser(self._page) class _FakePlaywright: def __init__(self, page: _FakePage) -> None: self.chromium = _FakeChromium(page) class _FakeAsyncPlaywright: def __init__(self, page: _FakePage) -> None: self._pw = _FakePlaywright(page) async def __aenter__(self) -> _FakePlaywright: return self._pw async def __aexit__(self, *_: object) -> None: ... class _FakePlaywrightTimeoutError(Exception): """Узкий класс, чтобы `except PlaywrightTimeoutError` не ловил всё подряд.""" def _patch_playwright( monkeypatch: pytest.MonkeyPatch, *, price: str = "12 500,50 ₽", days: str = "5-7 дней" ) -> _FakePage: page = _FakePage(price, days) fake_module = SimpleNamespace( async_playwright=lambda: _FakeAsyncPlaywright(page), TimeoutError=_FakePlaywrightTimeoutError, ) monkeypatch.setitem(sys.modules, "playwright", SimpleNamespace(async_api=fake_module)) monkeypatch.setitem(sys.modules, "playwright.async_api", fake_module) return page def test_health_no_auth(client: TestClient) -> None: response = client.get("/health") assert response.status_code == 200 assert response.json() == {"ok": True} def test_scrape_happy_path(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: page = _patch_playwright(monkeypatch) response = client.post( "/scrape", json=VALID_BODY, headers={"Authorization": "Bearer secret-test"}, ) assert response.status_code == 200, response.text body = response.json() assert body == {"price_rub": "12500.50", "days_min": 5, "days_max": 7} fills = [c for c in page.calls if c[0] == "fill"] assert ("fill", VALID_SELECTORS["from_city"], "Алматы") in fills assert ("fill", VALID_SELECTORS["to_city"], "Москва") in fills assert ("fill", VALID_SELECTORS["places"], "5") in fills def test_scrape_without_token_401(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: _patch_playwright(monkeypatch) response = client.post("/scrape", json=VALID_BODY) assert response.status_code == 401 assert response.json()["detail"] == "invalid token" def test_scrape_wrong_token_401(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: _patch_playwright(monkeypatch) response = client.post("/scrape", json=VALID_BODY, headers={"Authorization": "Bearer wrong"}) assert response.status_code == 401 def test_scrape_missing_token_env_503(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("PEK_SCRAPER_TOKEN", raising=False) _patch_playwright(monkeypatch) client = TestClient(scraper_app.app) response = client.post("/scrape", json=VALID_BODY, headers={"Authorization": "Bearer anything"}) assert response.status_code == 503 def test_scrape_missing_selector_400(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: _patch_playwright(monkeypatch) bad_body = { **VALID_BODY, "selectors": {k: v for k, v in VALID_SELECTORS.items() if k != "submit"}, } response = client.post( "/scrape", json=bad_body, headers={"Authorization": "Bearer secret-test"} ) assert response.status_code == 400 assert "submit" in response.json()["detail"] def test_scrape_unparseable_price_502(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: _patch_playwright(monkeypatch, price="нет цены", days="5-7") response = client.post( "/scrape", json=VALID_BODY, headers={"Authorization": "Bearer secret-test"} ) assert response.status_code == 502 assert "parse" in response.json()["detail"] def test_scrape_invalid_qty_422(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: _patch_playwright(monkeypatch) bad_body = {**VALID_BODY, "places_count": 0} response = client.post( "/scrape", json=bad_body, headers={"Authorization": "Bearer secret-test"} ) assert response.status_code == 422