From 2e72b40739a9598f6b8cfede8510e796008de42c Mon Sep 17 00:00:00 2001 From: bowu Date: Sat, 3 Jun 2023 21:02:06 +0800 Subject: [PATCH] Improvement: extend pytest.raises to support Exception having __repr__ method and initialized with kwargs parameter, except default repr. --- src/_pytest/_code/code.py | 5 ++++- testing/python/raises.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index 75076b4cc..c3c9b2c49 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -709,7 +709,10 @@ class ExceptionInfo(Generic[E]): __tracebackhide__ = True value = str(self.value) if not value: - value = repr(self.value) + repr_value = repr(self.value) + default_repr = f"{self.type.__name__}()" + if repr_value != default_repr: + value = repr_value msg = f"Regex pattern did not match.\n Regex: {regexp!r}\n Input: {value!r}" if regexp == value: msg += "\n Did you mean to `re.escape()` the regex?" diff --git a/testing/python/raises.py b/testing/python/raises.py index 76958e79a..3dcec31eb 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -173,7 +173,7 @@ class TestRaises: if method == "function": pytest.raises(ValueError, t) elif method == "function_match": - pytest.raises(ValueError, t).match(r"ValueError\(\)") + pytest.raises(ValueError, t).match("^$") else: with pytest.raises(ValueError): t()