Skip to content

Commit 9c5b57b

Browse files
authored
Merge pull request #2153 from elovelan/fix/xfail_side_effects
Defer xfail condition evaluation with xfail_if_raises context manager
2 parents 514a9de + 03baced commit 9c5b57b

2 files changed

Lines changed: 388 additions & 360 deletions

File tree

test/lib/helper.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
"skipIf",
1919
"GIT_REPO",
2020
"GIT_DAEMON_PORT",
21+
"xfail_if_raises",
2122
]
2223

2324
import contextlib
@@ -35,8 +36,10 @@
3536
import time
3637
import unittest
3738
import venv
39+
from typing import Union, Type, Tuple
3840

3941
import gitdb
42+
import pytest
4043

4144
from git.util import rmtree, cwd
4245

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

0 commit comments

Comments
 (0)