"""pytest 测试分层示例；直接运行或 python -m pytest 本文件。"""
import asyncio
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
from unittest.mock import Mock
import pytest


def parse_status(text):
    value = int(text)
    if not 100 <= value <= 599:
        raise ValueError("status outside contract")
    return value


def fetch_status(transport):
    # 单元替身只证明调用约定，不证明真的存在远程 HTTP 服务。
    return parse_status(transport.get("/health"))


@pytest.mark.parametrize("text,expected", [("200", 200), ("500", 500)])
def test_status_valid(text, expected):
    assert parse_status(text) == expected


@pytest.mark.parametrize("text", ["slow", "99", "600"])
def test_status_invalid(text):
    with pytest.raises(ValueError):
        parse_status(text)


def test_transport_contract():
    transport = Mock()
    transport.get.return_value = "200"
    assert fetch_status(transport) == 200
    transport.get.assert_called_once_with("/health")


@pytest.fixture
def database(tmp_path):
    connection = sqlite3.connect(tmp_path / "events.db")
    try:
        connection.execute("CREATE TABLE events(id INTEGER PRIMARY KEY, status INTEGER)")
        yield connection
    finally:
        connection.close()


def test_commit(database):
    with database:
        database.execute("INSERT INTO events VALUES(1,200)")
    assert database.execute("SELECT status FROM events").fetchall() == [(200,)]


def test_rollback(database):
    with pytest.raises(sqlite3.IntegrityError):
        with database:
            database.execute("INSERT INTO events VALUES(1,200)")
            database.execute("INSERT INTO events VALUES(1,500)")
    assert database.execute("SELECT COUNT(*) FROM events").fetchone()[0] == 0


def test_async_cancellation_cleanup():
    async def scenario():
        started = asyncio.Event()
        cleaned = asyncio.Event()
        async def worker():
            try:
                started.set()
                await asyncio.Event().wait()
            finally:
                cleaned.set()
        task = asyncio.create_task(worker())
        await asyncio.wait_for(started.wait(), timeout=2)
        task.cancel()
        with pytest.raises(asyncio.CancelledError):
            await task
        assert cleaned.is_set()
        assert task.done()
    asyncio.run(scenario())  # 每次有自己的 loop，不依赖异步 pytest 插件。


def test_cli_end_to_end(tmp_path):
    config = tmp_path / "config.json"
    config.write_text('{"limit": 1}', encoding="utf-8")
    (tmp_path / "events.jsonl").write_text('{"at":"2026-01-01T08:00:00+08:00"}\n', encoding="utf-8")
    cli = Path(__file__).with_name("25_cli.py")
    launch = tmp_path / "launch"
    launch.mkdir()
    environment = dict(os.environ, PYTHONIOENCODING="utf-8")
    environment.pop("SERIES_LIMIT", None)
    result = subprocess.run([sys.executable, str(cli.resolve()), "--config", str(config),
                             "--input", "events.jsonl"], cwd=launch,
                            env=environment,
                            capture_output=True, text=True, timeout=10)
    assert result.returncode == 0, result.stderr
    assert json.loads(result.stdout) == {"total": 1, "times": ["2026-01-01T00:00:00+00:00"]}


if __name__ == "__main__":
    raise SystemExit(pytest.main([str(Path(__file__).resolve()), "-q"]))
