Buckets:
| """Project-level pytest configuration hooks.""" | |
| import atexit | |
| import logging | |
| import os | |
| import re | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| from typing import Any | |
| from unittest import mock | |
| # ============================================================================= | |
| # HOME isolation (MUST happen before ANY pdd.* import) | |
| # ============================================================================= | |
| # Pin HOME (and CODEX_HOME) to a per-pytest-session sandbox tempdir BEFORE any | |
| # pdd.* module is imported below. Two production modules compute paths via | |
| # ``Path.home()`` at *import time* — ``pdd/auth_service.py:20`` and | |
| # ``pdd/get_jwt_token.py:74`` both define | |
| # ``JWT_CACHE_FILE = Path.home() / ".pdd" / "jwt_cache"`` — and | |
| # ``_save_api_key()`` in ``pdd/cli_detector.py:463-491`` writes to | |
| # ``~/.pdd/api-env.{shell}`` and appends to ``~/.bashrc`` / ``~/.zshrc`` / | |
| # ``~/.config/fish/config.fish``. Without HOME pinning before those modules | |
| # load, the constants capture the developer's real home and any test that | |
| # exercises the write paths (directly or transitively via CLI bootstrap) | |
| # would overwrite real shell rc / token cache files. | |
| # | |
| # A parallel fix shipped in promptdriven/pdd_cloud#1486 for the same class of | |
| # bug — a test fixture overwrote ~/.codex/auth.json with a placeholder token | |
| # and broke the developer's Codex CLI until they re-ran ``codex login``. | |
| # ``tests/test_home_isolation.py`` pins these invariants. | |
| _PYTEST_FAKE_HOME = tempfile.mkdtemp(prefix="pdd-pytest-home-") | |
| atexit.register(shutil.rmtree, _PYTEST_FAKE_HOME, ignore_errors=True) | |
| os.environ["HOME"] = _PYTEST_FAKE_HOME | |
| os.environ["CODEX_HOME"] = os.path.join(_PYTEST_FAKE_HOME, ".codex") | |
| import pytest | |
| from dotenv import load_dotenv | |
| from pdd.llm_invoke import InsufficientCreditsError | |
| CANDIDATE_ONLY_SOURCE_MODE = "candidate-tree-v1" | |
| def authenticated_candidate_missing_refs(root: Path, *refs: str) -> tuple[str, ...]: | |
| """Return absent refs only for the exact authenticated candidate checkout.""" | |
| missing_refs = [ | |
| ref | |
| for ref in refs | |
| if subprocess.run( | |
| ["git", "cat-file", "-e", f"{ref}^{{commit}}"], | |
| cwd=root, | |
| check=False, | |
| capture_output=True, | |
| ).returncode | |
| != 0 | |
| ] | |
| if not missing_refs or os.getenv("PDD_CLOUD_SOURCE_IDENTITY_MODE") != ( | |
| CANDIDATE_ONLY_SOURCE_MODE | |
| ): | |
| return () | |
| candidate_sha = os.getenv("PDD_CANDIDATE_SHA", "") | |
| candidate_tree = os.getenv("PDD_CANDIDATE_TREE", "") | |
| if re.fullmatch(r"[0-9a-f]{40}", candidate_sha) is None or re.fullmatch( | |
| r"[0-9a-f]{40}", candidate_tree | |
| ) is None: | |
| return () | |
| actual_identity = subprocess.run( | |
| ["git", "rev-parse", "HEAD^{commit}", "HEAD^{tree}"], | |
| cwd=root, | |
| check=False, | |
| capture_output=True, | |
| text=True, | |
| ) | |
| if actual_identity.returncode != 0: | |
| return () | |
| if actual_identity.stdout.splitlines() == [candidate_sha, candidate_tree]: | |
| return tuple(missing_refs) | |
| return () | |
| def skip_if_authenticated_candidate_lacks_refs( | |
| root: Path, purpose: str, *refs: str | |
| ) -> None: | |
| """Skip absent history only for the exact authenticated candidate checkout.""" | |
| missing_refs = authenticated_candidate_missing_refs(root, *refs) | |
| if missing_refs: | |
| pytest.skip(f"requires {purpose}: " + ", ".join(missing_refs)) | |
| class _MiniMocker: | |
| """Small pytest-mock compatible subset used by this test suite.""" | |
| Mock = mock.Mock | |
| MagicMock = mock.MagicMock | |
| def __init__(self) -> None: | |
| self._patchers: list[Any] = [] | |
| def patch(self, target: str, *args, **kwargs): | |
| patcher = mock.patch(target, *args, **kwargs) | |
| self._patchers.append(patcher) | |
| return patcher.start() | |
| def spy(self, obj: Any, attribute: str): | |
| original = getattr(obj, attribute) | |
| patcher = mock.patch.object(obj, attribute, wraps=original) | |
| self._patchers.append(patcher) | |
| return patcher.start() | |
| def stopall(self) -> None: | |
| while self._patchers: | |
| self._patchers.pop().stop() | |
| def mocker(): | |
| """Fallback mocker fixture for environments without pytest-mock.""" | |
| helper = _MiniMocker() | |
| try: | |
| yield helper | |
| finally: | |
| helper.stopall() | |
| # Load environment variables from .env early in collection. | |
| # Note: python-dotenv's default ``override=False`` won't clobber the HOME / | |
| # CODEX_HOME values we just pinned above. | |
| load_dotenv() | |
| # Store the original PDD_PATH at module load time for restoration | |
| _ORIGINAL_PDD_PATH = os.environ.get('PDD_PATH') | |
| # Store original streams at module load time for restoration | |
| _ORIGINAL_STDOUT = sys.stdout | |
| _ORIGINAL_STDERR = sys.stderr | |
| _ORIGINAL_GIT_WORK_TREE = os.environ.get('GIT_WORK_TREE') | |
| _E2E_FIX_ORIGINAL_ATTRS: dict[str, Any] | None = None | |
| _E2E_FIX_ATTRS_TO_RESTORE = ( | |
| "run_agentic_task", | |
| "load_prompt_template", | |
| "console", | |
| "load_workflow_state", | |
| "save_workflow_state", | |
| "clear_workflow_state", | |
| "_get_file_hashes", | |
| "_detect_changed_files", | |
| "_detect_meaningful_changes", | |
| "_commit_and_push", | |
| "_check_e2e_environment", | |
| "classify_step_output", | |
| "post_final_comment", | |
| "_run_step11_code_cleanup", | |
| "run_ci_validation_loop", | |
| ) | |
| def _enforce_isolated_home(monkeypatch): | |
| """Per-test re-assertion of HOME/CODEX_HOME isolation. | |
| The module-level pinning at the top of this file handles | |
| import-time path resolution. This fixture defends against tests that | |
| explicitly mutate HOME (e.g. ``os.environ["HOME"] = "..."``) by | |
| restoring the sandbox before the next test runs. | |
| """ | |
| monkeypatch.setenv("HOME", _PYTEST_FAKE_HOME) | |
| monkeypatch.setenv("CODEX_HOME", os.path.join(_PYTEST_FAKE_HOME, ".codex")) | |
| def sandbox_home() -> Path: | |
| """Expose the session-scoped fake HOME pinned at conftest import time. | |
| Regression tests in ``tests/test_home_isolation.py`` assert that | |
| HOME / CODEX_HOME / ``Path.home()`` / module-level JWT_CACHE_FILE | |
| constants all resolve to exactly this path. Asserting equality | |
| against this fixture (rather than a hard-coded temp-root whitelist | |
| like ``/tmp/``) keeps the invariant robust against CI/dev | |
| environments with a custom ``TMPDIR``. | |
| """ | |
| return Path(_PYTEST_FAKE_HOME) | |
| def restore_agentic_e2e_fix_orchestrator_mocks(): | |
| """Restore orchestrator globals that heavily mocked tests replace. | |
| The public CI unit-test job runs many orchestrator regression modules in | |
| shared xdist workers. If a mock of file-change detection leaks past one | |
| test, later end-to-end tests can think a fix was applied and skip their | |
| no-progress guards. Keep the cleanup centralized so those tests remain | |
| order-independent. | |
| """ | |
| global _E2E_FIX_ORIGINAL_ATTRS | |
| try: | |
| import pdd.agentic_e2e_fix_orchestrator as orchestrator | |
| except ImportError: | |
| yield | |
| return | |
| if _E2E_FIX_ORIGINAL_ATTRS is None: | |
| _E2E_FIX_ORIGINAL_ATTRS = { | |
| attr: getattr(orchestrator, attr) | |
| for attr in _E2E_FIX_ATTRS_TO_RESTORE | |
| if hasattr(orchestrator, attr) | |
| } | |
| yield | |
| for attr, original in _E2E_FIX_ORIGINAL_ATTRS.items(): | |
| setattr(orchestrator, attr, original) | |
| def _restore_logger_levels(): | |
| """Prevent log-level pollution from leaking across shared xdist workers. | |
| Quiet/estimate code paths lower process-wide logger levels and never restore | |
| them: ``pdd.core.cli``'s quiet branch sets ``logging.getLogger("pdd")`` to | |
| ``ERROR`` and ``pdd.llm_invoke.set_quiet_logging`` does the same for the | |
| ``pdd.llm_invoke`` and ``litellm`` loggers. Because estimate mode forces | |
| quiet, any CLI estimate/quiet test silences INFO records for every later | |
| test in the same worker — so ``caplog``-based assertions (e.g. | |
| ``test_change_main``, ``test_issue_225``) see an empty ``caplog.text`` and | |
| fail order-dependently in the public CI run. Snapshot and restore the levels | |
| of the pdd/litellm logger subtrees (and root) around each test so one test's | |
| quiet configuration cannot bleed into the next. | |
| """ | |
| names = {"", "pdd", "pdd.llm_invoke", "litellm"} | |
| names.update( | |
| name | |
| for name in list(logging.Logger.manager.loggerDict) | |
| if name in ("pdd", "litellm") or name.startswith(("pdd.", "litellm.")) | |
| ) | |
| saved = {name: logging.getLogger(name).level for name in names} | |
| yield | |
| for name, level in saved.items(): | |
| logging.getLogger(name).setLevel(level) | |
| def preserve_cwd(): | |
| """Restore cwd after each test so xdist workers don't leak temp dirs. | |
| Several tests intentionally chdir into throwaway workspaces. When one of | |
| those tests leaves the worker process outside the repository, later tests | |
| that read committed relative paths such as ``pdd/data/llm_model.csv`` fail | |
| order-dependently in the full public CI run. | |
| """ | |
| original_cwd = os.getcwd() | |
| yield | |
| try: | |
| os.chdir(original_cwd) | |
| except FileNotFoundError: | |
| os.chdir(Path(__file__).resolve().parents[1]) | |
| def preserve_git_work_tree(): | |
| """Clear GIT_WORK_TREE during tests to avoid interfering with git init in temp dirs.""" | |
| os.environ.pop('GIT_WORK_TREE', None) | |
| yield | |
| if _ORIGINAL_GIT_WORK_TREE is not None: | |
| os.environ['GIT_WORK_TREE'] = _ORIGINAL_GIT_WORK_TREE | |
| else: | |
| os.environ.pop('GIT_WORK_TREE', None) | |
| def isolate_cloud_only_overrides(monkeypatch): | |
| """Clear developer/CI env flags unless a test sets them. | |
| ``PDD_QUIET`` is included because the Cloud Batch worker exports it | |
| globally. Without this, tests that exercise the *non-quiet* user-facing | |
| console output (e.g. the unresolved-include warning in | |
| ``test_preprocess.py``) inherit the CI quiet flag and assert against an | |
| empty stdout — passing locally but failing in Cloud Batch. Tests that | |
| need quiet mode still ``monkeypatch.setenv("PDD_QUIET", "1")`` after this | |
| autouse fixture runs, so their behavior is unchanged. | |
| """ | |
| monkeypatch.delenv("PDD_CLOUD_ONLY", raising=False) | |
| monkeypatch.delenv("PDD_NO_LOCAL_FALLBACK", raising=False) | |
| monkeypatch.delenv("PDD_QUIET", raising=False) | |
| def _isolate_provider_env(monkeypatch): | |
| """Clear every provider credential env var the OpenCode code path consults. | |
| Fix C of ``promptdriven/pdd_cloud#1405``: the autonomous-solve PR | |
| ``promptdriven/pdd#858`` shipped tests that passed in the verifier's | |
| minimal worker container but failed on any developer machine that had | |
| real provider keys exported (``XAI_API_KEY``, | |
| ``GOOGLE_APPLICATION_CREDENTIALS``, ``VERTEXAI_PROJECT``, ...). The | |
| tests silently assumed "this env var happens to be unset"; this | |
| fixture makes that assumption explicit by always clearing the | |
| canonical key set before each test runs. | |
| Canonical source | |
| ---------------- | |
| The key set is sourced from | |
| ``pdd.agentic_common._opencode_provider_env_keys()`` — the same helper | |
| the production code path uses to decide whether to trust an OpenCode | |
| credential signal. Using the runtime helper (not the smaller 26-key | |
| ``_OPENCODE_PROVIDER_ENV_KEYS_FALLBACK`` constant) means every provider | |
| row added to ``pdd/data/llm_model.csv`` is automatically covered, and | |
| the Fix B static-analysis detector | |
| (``promptdriven/pdd#899``) does not flag this fixture as drift. | |
| Opt-back-in | |
| ----------- | |
| Tests that need a credential set (most ``test_agentic_common.py`` | |
| "has credentials" cases, every Issue #813 ``_isolated_env`` test) | |
| populate it explicitly via ``monkeypatch.setenv`` or | |
| ``patch.dict(os.environ, {...})``. Because pytest tears down fixtures | |
| in reverse order, an inner ``patch.dict`` undoes before this fixture's | |
| teardown, so neither path sees the developer's real env leak in. | |
| Why this fixture also imports lazily | |
| ------------------------------------- | |
| Importing ``pdd.agentic_common`` at conftest import time would pull | |
| in litellm and other heavy modules even for trivial test sessions. | |
| The import is deferred to first-fixture-use, which keeps test | |
| collection fast and matches the lazy-import pattern already used by | |
| ``_isolate_claude_oauth_probe``. | |
| """ | |
| # Lazy import: avoid pulling litellm into conftest's import graph. | |
| # See module docstring for the rationale. | |
| from pdd.agentic_common import ( | |
| _opencode_provider_env_keys, | |
| reset_disabled_providers, | |
| ) | |
| for key in _opencode_provider_env_keys(): | |
| monkeypatch.delenv(key, raising=False) | |
| # Issue #1936: the run-scoped permanent-provider-failure registry lives in a | |
| # module global AND the PDD_AGENTIC_DISABLED_PROVIDERS env var. A test that | |
| # induces a permanent provider error would otherwise leak a disabled provider | |
| # into later tests in the same session. Clear both before every test. | |
| monkeypatch.delenv("PDD_AGENTIC_DISABLED_PROVIDERS", raising=False) | |
| reset_disabled_providers() | |
| def _isolate_cli_binary_presence(request, monkeypatch): | |
| """Default every agentic CLI binary to "not installed" and the OpenCode | |
| filesystem credential signals to "absent" before each test. | |
| Fix A-prime of ``promptdriven/pdd_cloud#1405``: the autonomous-solve PR | |
| ``promptdriven/pdd#858`` shipped 4 tests in ``test_agentic_common.py`` | |
| that silently passed only because the verifier's minimal worker | |
| container had no agentic CLIs installed under ``~/.local/bin`` and | |
| no OpenCode auth file at ``~/.local/share/opencode/auth.json``. On a | |
| developer machine where the user had ``npm install -g opencode-ai``'d | |
| the CLI or run ``opencode auth login``, those tests would have leaked | |
| real filesystem state — passing for the wrong reason or failing | |
| surprisingly. Fix B (``promptdriven/pdd#899``) and Fix C | |
| (``promptdriven/pdd#902``) cover the env-var-leak shape; this fixture | |
| covers the CLI-binary-presence + auth-file shape. | |
| Canonical source | |
| ---------------- | |
| The agentic-CLI name set is sourced from | |
| ``pdd.cli_detector.CLI_PREFERENCE`` — the same ordered list the | |
| production CLI-detection path consults. Using the public constant | |
| (not a duplicate hardcoded literal) means a new agentic CLI added | |
| to the codebase is automatically isolated and the Fix B static- | |
| analysis detector does not flag this fixture as drift. | |
| What gets isolated | |
| ------------------- | |
| 1. ``pdd.agentic_common._find_cli_binary(name)`` returns ``None`` for | |
| every name in ``CLI_PREFERENCE``. Non-agentic names (``git``, | |
| ``sh``, ...) pass through to the real implementation so legitimate | |
| subprocess tests are unaffected. | |
| 2. ``pdd.agentic_common._opencode_auth_file_has_credentials`` returns | |
| ``False`` unconditionally. | |
| 3. ``pdd.agentic_common._iter_opencode_config_texts`` yields an empty | |
| iterable unconditionally. | |
| Opt-back-in | |
| ----------- | |
| Tests that need a CLI to be "installed" or credentials to be present | |
| override these via ``monkeypatch.setattr`` after the autouse fixture | |
| runs, or use the existing per-test fixtures in | |
| ``test_agentic_common.py`` (``mock_shutil_which`` patches | |
| ``_find_cli_binary``; ``mock_env`` patches the credential helpers). | |
| Both compose correctly with this autouse fixture — explicit per-test | |
| patches replace our defaults and unwind before our teardown. | |
| Why this fixture imports lazily | |
| -------------------------------- | |
| Importing ``pdd.agentic_common`` and ``pdd.cli_detector`` at conftest | |
| collection time would pull in litellm and other heavy modules even | |
| for trivial test sessions. The imports are deferred to first-fixture- | |
| use, matching the lazy-import pattern of ``_isolate_provider_env`` | |
| and ``_isolate_claude_oauth_probe``. | |
| Opt-out via marker | |
| ------------------ | |
| Tests that exercise ``_find_cli_binary`` itself (the production | |
| CLI-detection function — see ``TestCliDiscovery`` / ``TestCliDiscoveryBug``) | |
| must be able to run the real function with their own mocks underneath. | |
| Mark such tests/classes with ``@pytest.mark.uses_real_cli_detector`` | |
| to skip the autouse isolation. The marker is registered via | |
| ``pytest_configure`` below. | |
| """ | |
| if request.node.get_closest_marker("uses_real_cli_detector"): | |
| return # explicit opt-out for tests that exercise the real CLI detector | |
| # Lazy imports: avoid pulling agentic_common / cli_detector into | |
| # conftest's import graph. See docstring for rationale. | |
| import pdd.agentic_common as ac | |
| from pdd.cli_detector import CLI_PREFERENCE | |
| agentic_clis = frozenset(CLI_PREFERENCE) | |
| real_find = ac._find_cli_binary | |
| def _isolated_find(name, *args, **kwargs): | |
| if name in agentic_clis: | |
| return None | |
| return real_find(name, *args, **kwargs) | |
| monkeypatch.setattr(ac, "_find_cli_binary", _isolated_find, raising=True) | |
| monkeypatch.setattr( | |
| ac, "_opencode_auth_file_has_credentials", lambda path: False, raising=True | |
| ) | |
| monkeypatch.setattr( | |
| ac, "_iter_opencode_config_texts", lambda cwd=None: iter(()), raising=True | |
| ) | |
| def _isolate_claude_oauth_probe(monkeypatch): | |
| """Default the Issue #813 OAuth probe to False so tests are CI-portable. | |
| On developer machines and CI runners that have ``claude`` installed and | |
| logged in via Max/Pro, the probe in ``_strip_anthropic_creds_for_claude_subprocess`` | |
| would otherwise pop ANTHROPIC_API_KEY out of the subprocess env and break | |
| legacy tests that assert the key survives (e.g. ``test_environment_sanitization``). | |
| Tests that exercise the strip behavior re-patch ``_claude_has_oauth_login`` | |
| or ``_probe_claude_auth_status`` to True/non-empty in their own scope. | |
| """ | |
| monkeypatch.setattr("pdd.agentic_common._claude_has_oauth_login", lambda: False) | |
| def _isolate_codex_auth_file(monkeypatch): | |
| """Default ``_has_codex_auth_file`` to False (Issue #813 round-6). | |
| Developer machines often have ``~/.codex/auth.json`` from a real | |
| ``codex login``. Without this fixture, ``test_get_available_agents_*`` | |
| tests that assume "no auth signal" pick up the dev's real codex | |
| login and incorrectly report openai available, breaking | |
| deterministic test runs across environments. | |
| """ | |
| monkeypatch.setattr("pdd.agentic_common._has_codex_auth_file", lambda: False) | |
| def preserve_pdd_path(): | |
| """Ensure PDD_PATH is restored after each test to prevent test pollution. | |
| Always restores to the original PDD_PATH that was present when conftest loaded, | |
| regardless of what other fixtures or tests did during the test. | |
| """ | |
| yield | |
| # Always restore original PDD_PATH after each test | |
| if _ORIGINAL_PDD_PATH is not None: | |
| os.environ['PDD_PATH'] = _ORIGINAL_PDD_PATH | |
| elif 'PDD_PATH' in os.environ: | |
| # Original was None but test set it - remove it | |
| del os.environ['PDD_PATH'] | |
| def restore_standard_streams(): | |
| """Ensure sys.stdout/stderr are restored after each test to prevent pollution. | |
| CLI code may wrap streams with OutputCapture for core dump functionality. | |
| If early exits (ctx.exit(0)) bypass normal cleanup, streams remain wrapped. | |
| This fixture provides defense-in-depth by restoring original streams. | |
| """ | |
| yield | |
| # Restore if streams were replaced (indicates incomplete cleanup) | |
| # Import here to avoid circular imports at module load time | |
| try: | |
| from pdd.core.cli import OutputCapture | |
| if isinstance(sys.stdout, OutputCapture): | |
| sys.stdout = _ORIGINAL_STDOUT | |
| if isinstance(sys.stderr, OutputCapture): | |
| sys.stderr = _ORIGINAL_STDERR | |
| except ImportError: | |
| # If OutputCapture can't be imported, fall back to simple check | |
| if sys.stdout is not _ORIGINAL_STDOUT: | |
| sys.stdout = _ORIGINAL_STDOUT | |
| if sys.stderr is not _ORIGINAL_STDERR: | |
| sys.stderr = _ORIGINAL_STDERR | |
| def pytest_addoption(parser: pytest.Parser) -> None: | |
| """Expose the legacy ``--run-all`` flag expected by our tooling.""" | |
| parser.addoption( | |
| "--run-all", | |
| action="store_true", | |
| default=False, | |
| help="Run the full suite including slow or integration tests.", | |
| ) | |
| parser.addoption( | |
| "--durable-max-parallel", | |
| action="store", | |
| type=int, | |
| default=None, | |
| help="Override durable sync runner concurrency in durable verification tests.", | |
| ) | |
| def durable_max_parallel(request: pytest.FixtureRequest) -> int | None: | |
| """Return the optional durable runner concurrency override.""" | |
| return request.config.getoption("--durable-max-parallel") | |
| def pytest_configure(config: pytest.Config) -> None: | |
| """Configure pytest: mirror --run-all flag. | |
| Note: JWT auto-population was removed to prevent browser popups during | |
| test runs (especially from test explorers like VS Code/PyCharm). | |
| Tests needing auth should mock it or use PDD_JWT_TOKEN env var. | |
| """ | |
| run_all: Any = config.getoption("--run-all") | |
| if run_all: | |
| os.environ["PDD_RUN_ALL_TESTS"] = "1" | |
| else: | |
| os.environ.setdefault("PDD_RUN_ALL_TESTS", "0") | |
| # Fix A-prime (promptdriven/pdd_cloud#1405): register the opt-out marker | |
| # for tests that exercise the real CLI-detection path with their own | |
| # mocks underneath (TestCliDiscovery / TestCliDiscoveryBug). See the | |
| # ``_isolate_cli_binary_presence`` fixture docstring for context. | |
| config.addinivalue_line( | |
| "markers", | |
| "uses_real_cli_detector: skip the Fix A-prime autouse CLI-binary " | |
| "isolation fixture; for tests that test _find_cli_binary itself.", | |
| ) | |
| # Per-story outcome tallies for the story regression lane (``pytest -m story``). | |
| # Keyed by story id; each value is a {"passed"/"failed"/"skipped": count} bucket. | |
| # Populated in ``pytest_runtest_makereport`` and rendered by | |
| # ``pytest_terminal_summary``. Only meaningful when the lane runs without xdist | |
| # (the story lane in ``tests/story_regression.sh`` runs single-process so this | |
| # module-level state is shared across the whole session). | |
| _STORY_RESULTS: dict[str, dict[str, int]] = {} | |
| def _story_id(item: pytest.Item, marker: pytest.Mark) -> str: | |
| """Resolve a human-readable story identifier from the ``story`` marker. | |
| Accepts ``@pytest.mark.story("checkout")``, ``@pytest.mark.story(story_id=...)`` | |
| (the form every generated story test actually uses), ``name=...``, or | |
| ``id=...``; falls back to the test's file path so a bare ``@pytest.mark.story`` | |
| still groups sensibly per module. Without ``story_id`` the summary silently | |
| counted files instead of stories (pdd#1889 V-F4). | |
| """ | |
| if marker.args: | |
| return str(marker.args[0]) | |
| if "story_id" in marker.kwargs: | |
| return str(marker.kwargs["story_id"]) | |
| if "name" in marker.kwargs: | |
| return str(marker.kwargs["name"]) | |
| if "id" in marker.kwargs: | |
| return str(marker.kwargs["id"]) | |
| return item.nodeid.split("::", 1)[0] | |
| def _story_report_counts(report) -> bool: | |
| """Whether *report* should contribute to the per-story tally. | |
| Counts the ``call`` phase normally, plus a skip that happens during the | |
| ``setup`` phase — a ``@pytest.mark.skip``-decorated story emits only a setup | |
| skip and no ``call`` report, so without this it would vanish from the summary | |
| entirely (pdd#1889 V-F4). A normal (non-skipped) setup phase is not counted, | |
| so passing tests are never double-counted. | |
| """ | |
| if report.when == "call": | |
| return True | |
| return report.when == "setup" and getattr(report, "skipped", False) | |
| def _story_summary_status(counts: dict) -> str: | |
| """Render the PASS/FAIL/SKIP verdict for a story's outcome bucket. | |
| A story that only skipped is SKIP, not PASS — reporting a skip-only story as | |
| ``[PASS] ...: 0 passed, 1 skipped`` overstated coverage (pdd#1889 V-F4). | |
| """ | |
| failed = counts.get("failed", 0) | |
| passed = counts.get("passed", 0) | |
| skipped = counts.get("skipped", 0) | |
| if failed: | |
| return "FAIL" | |
| if passed == 0 and skipped: | |
| return "SKIP" | |
| return "PASS" | |
| def pytest_runtest_makereport(item: pytest.Item, call): | |
| """Convert InsufficientCreditsError failures to skips and tally stories. | |
| The cloud batch test account may run out of credits, causing tests that call | |
| the production LLM endpoint to fail with InsufficientCreditsError. These are | |
| infrastructure failures, not code bugs — convert to skip rather than fail. | |
| Story-marked tests are additionally tallied per story so the story | |
| regression lane can emit a per-story pass/fail summary (issue #1701). | |
| """ | |
| outcome = yield | |
| report = outcome.get_result() | |
| if report.when == "call" and report.failed and call.excinfo is not None: | |
| exc_type_name = type(call.excinfo.value).__name__ | |
| exc_text = str(call.excinfo.value) | |
| if call.excinfo.errisinstance(InsufficientCreditsError) or ( | |
| exc_type_name in {"UsageError", "RuntimeError"} | |
| and "Insufficient credits" in exc_text | |
| ): | |
| report.outcome = "skipped" | |
| report.wasxfail = "" | |
| report.longrepr = f"Skipped: Insufficient credits for cloud LLM call" | |
| if _story_report_counts(report): | |
| marker = item.get_closest_marker("story") | |
| if marker is not None: | |
| bucket = _STORY_RESULTS.setdefault( | |
| _story_id(item, marker), | |
| {"passed": 0, "failed": 0, "skipped": 0}, | |
| ) | |
| bucket[report.outcome] = bucket.get(report.outcome, 0) + 1 | |
| def pytest_terminal_summary(terminalreporter, exitstatus, config) -> None: | |
| """Emit a per-story pass/fail summary for the story regression lane. | |
| Only renders when story-marked tests actually ran, so the regular unit-test | |
| run is unaffected. Reports the number of stories, the total number of story | |
| regression tests, and a PASS/FAIL line per story (issue #1701). | |
| """ | |
| if not _STORY_RESULTS: | |
| return | |
| total_tests = sum(sum(counts.values()) for counts in _STORY_RESULTS.values()) | |
| terminalreporter.write_sep("=", "Story Regression Summary") | |
| terminalreporter.write_line( | |
| f"Stories: {len(_STORY_RESULTS)} " | |
| f"Story regression tests: {total_tests}" | |
| ) | |
| for story in sorted(_STORY_RESULTS): | |
| counts = _STORY_RESULTS[story] | |
| failed = counts.get("failed", 0) | |
| status = _story_summary_status(counts) | |
| detail = f"{counts.get('passed', 0)} passed" | |
| if failed: | |
| detail += f", {failed} failed" | |
| if counts.get("skipped", 0): | |
| detail += f", {counts['skipped']} skipped" | |
| terminalreporter.write_line(f" [{status}] {story}: {detail}") | |
| # Ignore non-suite assets under tests/ during collection. | |
| # `tests/fixtures/` contains fixture source trees used by higher-level tests; | |
| # some of those fixtures intentionally include broken `test_*.py` files. | |
| # They must never be collected as part of the main pytest suite. | |
| # | |
| # NOTE: ``collect_ignore_glob`` only prunes directory *recursion*. It is | |
| # silently bypassed when a specific fixture file path is handed to pytest on | |
| # the command line (pytest forces collection of explicitly-named files), so it | |
| # cannot, on its own, stop the Cloud Batch chunker from crashing a chunk that | |
| # happens to include an intentionally-broken fixture such as | |
| # ``tests/fixtures/coverage_contracts/fake_tests/test_receipt_failed.py``. The | |
| # authoritative guard for that path lives in the chunker / entrypoint file-list | |
| # discovery (``ci/cloud-batch/balance-chunks.py`` and | |
| # ``ci/cloud-batch/entrypoint.sh``), which now exclude all of ``tests/fixtures/``. | |
| collect_ignore_glob = [ | |
| "csv/*", | |
| "fixtures/*", | |
| "*_fixed.py", | |
| "**/*_fixed.py", | |
| ] | |
| # --- Common fixtures for CLI tests --- | |
| from click.testing import CliRunner | |
| def create_dummy_files(tmp_path): | |
| """Fixture to create dummy files for testing.""" | |
| files = {} | |
| def _create_files(*filenames, content="dummy content"): | |
| for name in filenames: | |
| file_path = tmp_path / name | |
| file_path.parent.mkdir(parents=True, exist_ok=True) | |
| file_path.write_text(content) | |
| files[name] = file_path | |
| return files | |
| return _create_files | |
| def runner(): | |
| """Fixture to provide a CliRunner for testing Click commands.""" | |
| return CliRunner() | |
Xet Storage Details
- Size:
- 29 kB
- Xet hash:
- f458aba06a4594f645bbc01e4ca71c4cc5ef2bac267b1faf8f06317c181a9ce5
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.