Skip to content

Commit 46daafe

Browse files
elovelanOpenCode
andcommitted
Add xfail_if_raises context manager to defer xfail condition evaluation
The @pytest.mark.xfail decorator with raises=... evaluates its condition during test collection, which can trigger external calls (e.g., Git().config()) that have side effects. Introduce xfail_if_raises as a context manager that delays this evaluation until test execution time, and apply it to test_index_mutation. Co-authored-by: OpenCode <ai-agent@example.invalid>
1 parent e196f44 commit 46daafe

2 files changed

Lines changed: 387 additions & 360 deletions

File tree

test/lib/helper.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@
3535
import time
3636
import unittest
3737
import venv
38+
from typing import Union
3839

3940
import gitdb
41+
import pytest
4042

4143
from git.util import rmtree, cwd
4244

@@ -465,3 +467,27 @@ def _executable(self, basename):
465467
if osp.isfile(path) or osp.islink(path):
466468
return path
467469
raise RuntimeError(f"no regular file or symlink {path!r}")
470+
471+
472+
@contextlib.contextmanager
473+
def xfail_if_raises(
474+
condition: bool,
475+
*,
476+
raises: Union[type[BaseException], tuple[type[BaseException], ...]],
477+
reason: str = "",
478+
strict: bool = False,
479+
):
480+
"""Approximates the behavior of @pytest.mark.xfail(..., raises=...) as a context
481+
manager that can be used within a test, such as when the condition is complex or has
482+
side effects
483+
484+
One difference is it will not report XPASS if the test passes, but setting `strict`
485+
simulates it by raising an exception"""
486+
try:
487+
yield
488+
except raises:
489+
if condition:
490+
pytest.xfail(reason)
491+
raise
492+
if strict and condition:
493+
pytest.fail("[XPASS(strict)] " + reason)

0 commit comments

Comments
 (0)