| """Example pytest fixtures and test functions. |
| |
| A small but realistic conftest-style module showing common pytest patterns: |
| fixtures with different scopes, parametrization, and skip/xfail markers. |
| """ |
| from __future__ import annotations |
|
|
| import os |
| import tempfile |
| from pathlib import Path |
|
|
| import pytest |
|
|
|
|
| @pytest.fixture(scope="session") |
| def session_tmpdir() -> Path: |
| """Session-scoped temporary directory shared across all tests.""" |
| with tempfile.TemporaryDirectory(prefix="pytest-session-") as d: |
| yield Path(d) |
|
|
|
|
| @pytest.fixture |
| def sample_config() -> dict[str, object]: |
| """Per-test configuration dict.""" |
| return {"debug": True, "timeout": 30, "retries": 3} |
|
|
|
|
| @pytest.fixture |
| def env_var(monkeypatch: pytest.MonkeyPatch) -> str: |
| """Set and restore an environment variable for one test.""" |
| monkeypatch.setenv("APP_MODE", "test") |
| return os.environ["APP_MODE"] |
|
|
|
|
| @pytest.mark.parametrize("value,expected", [(1, 1), (2, 4), (3, 9), (4, 16)]) |
| def test_square(value: int, expected: int) -> None: |
| assert value * value == expected |
|
|
|
|
| def test_config_defaults(sample_config: dict[str, object]) -> None: |
| assert sample_config["debug"] is True |
| assert sample_config["timeout"] == 30 |
|
|
|
|
| def test_env_override(env_var: str) -> None: |
| assert env_var == "test" |
|
|
|
|
| @pytest.mark.skipif(os.name == "nt", reason="POSIX-only path semantics") |
| def test_session_dir_exists(session_tmpdir: Path) -> None: |
| assert session_tmpdir.exists() and session_tmpdir.is_dir() |
|
|