134 lines
5.1 KiB
Python
134 lines
5.1 KiB
Python
"""Fixtures communes et organisation des tests.
|
|
|
|
tests/unitaires/ sans base ni site : fonctions pures, specs Vega-Lite, outils
|
|
tests/integration/ PostgreSQL et/ou site (client HTTP de test), collecteur
|
|
avec l'API YouTube simulée
|
|
tests/non_regression/ références figées (specs, routes), migrations rejouées,
|
|
anciennes configurations, anomalies déjà corrigées
|
|
tests/outils/ données factices, client du site, collecteur simulé,
|
|
affichage de la progression
|
|
|
|
Chaque test reçoit le marqueur de son dossier : ``pytest -m unitaires``,
|
|
``-m integration`` ou ``-m non_regression`` (ou le chemin du dossier).
|
|
|
|
Les tests qui touchent PostgreSQL ont besoin de trois URL (base déjà créée
|
|
avec sql/bootstrap.sql) :
|
|
|
|
TEST_OWNER_URL, TEST_COLLECTOR_URL, TEST_WEB_URL
|
|
|
|
Sans elles, ces tests sont ignorés ; les tests purs tournent toujours.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
|
|
import psycopg
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
from shortstats import migrate
|
|
from shortstats.config import MigrateConfig, WebConfig
|
|
from shortstats.web.app import create_app
|
|
from shortstats.web.auth import hash_password
|
|
|
|
from .outils import progression
|
|
from .outils.base import seed_snapshots
|
|
from .outils.fake_youtube import FakeYouTube
|
|
from .outils.progression import pytest_addoption # noqa: F401 (options --progression)
|
|
from .outils.site import ORIGIN, PASSWORD, login
|
|
from .outils.specs import write_dump
|
|
|
|
CATEGORIES = ("unitaires", "integration", "non_regression")
|
|
|
|
|
|
def pytest_configure(config):
|
|
for name, text in (("unitaires", "sans base ni site"), ("integration", "PostgreSQL et/ou site"),
|
|
("non_regression", "références figées, migrations, anciennes données, anomalies corrigées")):
|
|
config.addinivalue_line("markers", f"{name}: {text}")
|
|
progression.register(config)
|
|
|
|
|
|
def pytest_collection_modifyitems(config, items):
|
|
"""Marqueur du dossier de chaque test (unitaires, integration, non_regression)."""
|
|
for item in items:
|
|
parts = item.path.parts
|
|
for name in CATEGORIES:
|
|
if name in parts:
|
|
item.add_marker(getattr(pytest.mark, name))
|
|
break
|
|
|
|
|
|
def pytest_sessionfinish(session, exitstatus):
|
|
write_dump() # specs gardées pour la vérification Vega-Lite (DUMP_SPECS)
|
|
|
|
|
|
OWNER = os.environ.get("TEST_OWNER_URL")
|
|
COLLECTOR = os.environ.get("TEST_COLLECTOR_URL")
|
|
WEB = os.environ.get("TEST_WEB_URL")
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def db_urls():
|
|
if not (OWNER and COLLECTOR and WEB):
|
|
message = "TEST_OWNER_URL / TEST_COLLECTOR_URL / TEST_WEB_URL non définies"
|
|
if os.environ.get("CI"): # en CI, une base absente est une erreur, pas un test ignoré
|
|
pytest.fail(message)
|
|
pytest.skip(message)
|
|
migrate.run(MigrateConfig(database_url=OWNER, timezone="Europe/Paris",
|
|
collector_role="shortstats_collector", web_role="shortstats_web"))
|
|
return {"owner": OWNER, "collector": COLLECTOR, "web": WEB}
|
|
|
|
|
|
@pytest.fixture()
|
|
def clean_db(db_urls):
|
|
with psycopg.connect(db_urls["owner"], autocommit=True) as conn:
|
|
conn.execute("TRUNCATE shortstats.comment_estimate, shortstats.snapshot_theme, shortstats.comment_theme, shortstats.comment, shortstats.video_snapshot, shortstats.video, shortstats.chart, shortstats.collect_request, shortstats.collect_run, shortstats.channel, shortstats.user_password")
|
|
conn.execute("DELETE FROM shortstats.theme")
|
|
conn.execute("""INSERT INTO shortstats.theme (name, patterns) VALUES
|
|
('Apothecary Diaries', ARRAY['apothecary diaries']),
|
|
('applepie', ARRAY['applepie'])""")
|
|
return db_urls
|
|
|
|
|
|
@pytest.fixture()
|
|
def fake():
|
|
return FakeYouTube()
|
|
|
|
|
|
@pytest.fixture()
|
|
def evo(app_client, clean_db):
|
|
seed_snapshots(clean_db["owner"])
|
|
login(app_client)
|
|
return app_client
|
|
|
|
|
|
@pytest.fixture()
|
|
def two_users(clean_db, tmp_path):
|
|
path = tmp_path / "users.txt"
|
|
path.write_text(f"alice:{hash_password(PASSWORD)}\nbob:{hash_password(PASSWORD)}\n")
|
|
cfg = WebConfig(database_url=clean_db["web"], secret_key="x" * 40, users_file=str(path),
|
|
session_max_age_s=3600, cookie_secure=False, login_max_failures=3, login_lock_minutes=15)
|
|
with TestClient(create_app(cfg), base_url=ORIGIN) as c:
|
|
yield c
|
|
|
|
|
|
@pytest.fixture()
|
|
def themed(evo):
|
|
"""evo00000000 à 11 : relevés de 1 h à 30 h, commentaires relevés et comptes par thème (seed_snapshots)."""
|
|
return evo
|
|
|
|
|
|
@pytest.fixture()
|
|
def users_file(tmp_path):
|
|
path = tmp_path / "users.txt"
|
|
path.write_text(f"# comptes\nalice:{hash_password(PASSWORD)}\nligne invalide\n")
|
|
return path
|
|
|
|
|
|
@pytest.fixture()
|
|
def app_client(clean_db, users_file):
|
|
cfg = WebConfig(database_url=clean_db["web"], secret_key="x" * 40, users_file=str(users_file),
|
|
session_max_age_s=3600, cookie_secure=False, login_max_failures=3, login_lock_minutes=15)
|
|
with TestClient(create_app(cfg), base_url=ORIGIN) as client:
|
|
yield client
|