#!/usr/bin/env python3
"""Unit tests for the pytest version guard script."""

# File: tests/unit/scripts/test_check_pytest_version.py
# Purpose: Ensure the version guard detects mismatches and handles edge cases.
# Context: Protects temp/test_data concurrency fixes that depend on pytest internals.

from __future__ import annotations

from pathlib import Path
from unittest.mock import patch

import pytest
from scripts import check_pytest_version as checker


@pytest.fixture
def temp_lock_file(tmp_path: Path) -> Path:
    """Create a temporary lock file for isolated tests."""

    lock = tmp_path / "pytest_version.lock"
    lock.write_text("8.4.2\n", encoding="utf-8")
    return lock


def test_check_pytest_version_matches(temp_lock_file: Path) -> None:
    """Returns success when the installed version matches the lock file."""

    with patch.object(checker, "_current_pytest_version", return_value="8.4.2"):
        exit_code = checker.check_pytest_version(lock_path=temp_lock_file)

    assert exit_code == 0


def test_check_pytest_version_mismatch(temp_lock_file: Path) -> None:
    """Returns failure and prints guidance when versions differ."""

    with patch.object(checker, "_current_pytest_version", return_value="8.5.0"):
        with patch("sys.stderr.write") as mock_stderr:
            exit_code = checker.check_pytest_version(lock_path=temp_lock_file)

    assert exit_code == 1
    # 確認: 出力がガイダンスを含んでいること
    emitted = "".join(arg[0] for arg, _ in mock_stderr.call_args_list)
    assert "expected" in emitted and "actual" in emitted


def test_missing_lock_file(tmp_path: Path) -> None:
    """Main function exits with dedicated code when lock file is absent."""

    missing_path = tmp_path / "missing.lock"
    env_var = checker.LOCK_PATH_ENV

    with patch.dict("os.environ", {env_var: str(missing_path)}):
        exit_code = checker.main([])

    assert exit_code == 2
