"""Testy příkazu `python -m poznavacky vytvor-spravce`.""" from __future__ import annotations import re import subprocess import sys from collections.abc import Iterator from pathlib import Path import pytest from flask import Flask from flask.testing import FlaskClient from poznavacky import cli, create_app from poznavacky import db as db_module from poznavacky.security import hash_password, verify_password HESLO = "silne-heslo-ucitelky" def _login(client: FlaskClient, email: str, password: str): page = client.get("/prihlaseni").get_data(as_text=True) match = re.search(r'name="csrf_token" value="([^"]+)"', page) assert match is not None return client.post( "/prihlaseni", data={"csrf_token": match.group(1), "email": email, "heslo": password}, ) @pytest.fixture def env( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> Iterator[dict[str, str]]: values = { "POZNAVACKY_SECRET_KEY": "klic-cli", "POZNAVACKY_DATA_DIR": str(tmp_path / "data"), } for key in ("POZNAVACKY_ADMIN_EMAIL", "POZNAVACKY_ADMIN_PASSWORD"): monkeypatch.delenv(key, raising=False) for key, value in values.items(): monkeypatch.setenv(key, value) yield values def _run( email: str | None, passwords: list[str], *, typed_email: str = "", ) -> tuple[int, list[str]]: secrets = iter(passwords) output: list[str] = [] code = cli.vytvor_spravce( email, prompt=lambda _msg: typed_email, prompt_secret=lambda _msg: next(secrets), out=output.append, ) return code, output def _users(app: Flask) -> list: conn = db_module.connect(app.config["DB_PATH"]) try: return conn.execute("SELECT * FROM uzivatele").fetchall() finally: conn.close() def test_creates_teacher_over_empty_db(env: dict[str, str]) -> None: code, output = _run(None, [HESLO, HESLO], typed_email=" U@Example.Test ") assert code == 0 assert HESLO not in " ".join(output) app = create_app(environ=env) rows = _users(app) assert len(rows) == 1 assert rows[0]["email"] == "u@example.test" assert rows[0]["role"] == "ucitelka" assert rows[0]["stav"] == "schvaleny" assert rows[0]["schvaleno_at"] is not None client = app.test_client() resp = _login(client, "u@example.test", HESLO) assert resp.status_code == 302 assert client.get("/admin").status_code == 200 def test_changes_password_and_invalidates_session( env: dict[str, str], ) -> None: assert _run("u@example.test", [HESLO, HESLO])[0] == 0 app = create_app(environ=env) client = app.test_client() _login(client, "u@example.test", HESLO) assert client.get("/admin").status_code == 200 conn = db_module.connect(app.config["DB_PATH"]) try: user_id = _users(app)[0]["id"] conn.execute( """ INSERT INTO tokeny_hesla (uzivatel_id, token_hash, vyprsi_at) VALUES (?, 'x', '2999-01-01T00:00:00+00:00') """, (user_id,), ) conn.commit() finally: conn.close() code, _ = _run("u@example.test", ["nove-heslo-123", "nove-heslo-123"]) assert code == 0 rows = _users(app) assert len(rows) == 1 assert verify_password(rows[0]["heslo_hash"], "nove-heslo-123") assert not verify_password(rows[0]["heslo_hash"], HESLO) assert client.get("/admin").status_code == 302 conn = db_module.connect(app.config["DB_PATH"]) try: token = conn.execute("SELECT pouzito_at FROM tokeny_hesla").fetchone() assert token["pouzito_at"] is not None finally: conn.close() def test_refuses_student_account(env: dict[str, str]) -> None: app = create_app(environ=env) conn = db_module.connect(app.config["DB_PATH"]) try: conn.execute( """ INSERT INTO uzivatele (email, heslo_hash, jmeno, prijmeni, role, stav) VALUES ('zak@example.test', ?, 'Žák', 'Testovací', 'zak', 'schvaleny') """, (hash_password("puvodni-heslo"),), ) conn.commit() finally: conn.close() code, _ = _run("zak@example.test", [HESLO, HESLO]) assert code == 1 row = _users(app)[0] assert row["role"] == "zak" assert verify_password(row["heslo_hash"], "puvodni-heslo") @pytest.mark.parametrize( "passwords", [[HESLO, HESLO + "x"], ["kratke", "kratke"]], ids=["neshodna", "kratka"], ) def test_rejects_bad_password( env: dict[str, str], passwords: list[str] ) -> None: code, _ = _run("u@example.test", passwords) assert code == 1 assert _users(create_app(environ=env)) == [] def test_missing_secret_key_fails( env: dict[str, str], monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.delenv("POZNAVACKY_SECRET_KEY") code, output = _run("u@example.test", [HESLO, HESLO]) assert code == 2 assert "POZNAVACKY_SECRET_KEY" in output[0] def test_main_without_subcommand_runs_server() -> None: called: list[bool] = [] assert cli.main([], run_server=lambda: called.append(True)) == 0 assert called == [True] def test_module_help_lists_subcommand() -> None: result = subprocess.run( [sys.executable, "-m", "poznavacky", "--help"], capture_output=True, text=True, check=True, ) assert "vytvor-spravce" in result.stdout