← back to Paul Conrad Archive

tests/conftest.py

52 lines

import json
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
FIX = Path(__file__).parent / "fixtures"

from conrad import config, db  # noqa: E402
from conrad.crawlers.base import Blocked  # noqa: E402


@pytest.fixture
def tmpdb(tmp_path, monkeypatch):
    p = tmp_path / "t.db"
    monkeypatch.setattr(config, "DB_PATH", p)
    conn = db.connect(p)
    db.init_db(conn)
    return conn


class FakeHttp:
    """Maps URL substrings -> (status, body) or an exception instance."""

    def __init__(self, routes: dict):
        self.routes = routes
        self.calls = []

    def _match(self, url, params=None):
        full = url + ("?" + json.dumps(params, sort_keys=True) if params else "")
        self.calls.append(full)
        for k, v in self.routes.items():
            if k in full:
                if isinstance(v, Exception):
                    raise v
                return v
        raise Blocked(f"no fake route for {full}")

    def get(self, url, params=None, **kw):
        return self._match(url, params)

    def get_json(self, url, params=None, **kw):
        st, body = self._match(url, params)
        return json.loads(body)


@pytest.fixture
def fix():
    return lambda name: (FIX / name).read_text()