Improvement: optimize error info of pytest.raises match to be more clear

This commit is contained in:
bowu 2023-06-05 20:39:28 +08:00
parent 2e72b40739
commit d675f6fd1b
3 changed files with 8 additions and 24 deletions

View File

@ -708,12 +708,7 @@ class ExceptionInfo(Generic[E]):
"""
__tracebackhide__ = True
value = str(self.value)
if not 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}"
msg = f"Regex pattern did not match.\n Regex: {regexp!r}\n str(exception): {value!r}"
if regexp == value:
msg += "\n Did you mean to `re.escape()` the regex?"
assert re.search(regexp, value), msg

View File

@ -67,20 +67,6 @@ def test_excinfo_from_exception_missing_traceback_assertion() -> None:
_pytest._code.ExceptionInfo.from_exception(ValueError())
class ExceptionHavingRepr(Exception):
def __init__(self, status_code: int):
self.status_code = status_code
def __repr__(self) -> str:
return f"status_code={self.status_code}"
def test_excinfo_from_keywords_exception() -> None:
with pytest.raises(ExceptionHavingRepr, match=r"404"):
kwargs_exception = ExceptionHavingRepr(status_code=404)
raise kwargs_exception
def test_excinfo_getstatement():
def g():
raise ValueError
@ -448,7 +434,7 @@ def test_match_raises_error(pytester: Pytester) -> None:
match = [
r"E .* AssertionError: Regex pattern did not match.",
r"E .* Regex: '\[123\]\+'",
r"E .* Input: 'division by zero'",
r"E .* str\(exception\): 'division by zero'",
]
result.stdout.re_match_lines(match)
result.stdout.no_fnmatch_line("*__tracebackhide__ = True*")

View File

@ -196,7 +196,7 @@ class TestRaises:
expr = (
"Regex pattern did not match.\n"
f" Regex: {msg!r}\n"
" Input: \"invalid literal for int() with base 10: 'asdf'\""
" str(exception): \"invalid literal for int() with base 10: 'asdf'\""
)
with pytest.raises(AssertionError, match="(?m)" + re.escape(expr)):
with pytest.raises(ValueError, match=msg):
@ -221,7 +221,10 @@ class TestRaises:
with pytest.raises(AssertionError, match="'foo"):
raise AssertionError("'bar")
(msg,) = excinfo.value.args
assert msg == '''Regex pattern did not match.\n Regex: "'foo"\n Input: "'bar"'''
assert (
msg
== '''Regex pattern did not match.\n Regex: "'foo"\n str(exception): "'bar"'''
)
def test_match_failure_exact_string_message(self):
message = "Oh here is a message with (42) numbers in parameters"
@ -232,7 +235,7 @@ class TestRaises:
assert msg == (
"Regex pattern did not match.\n"
" Regex: 'Oh here is a message with (42) numbers in parameters'\n"
" Input: 'Oh here is a message with (42) numbers in parameters'\n"
" str(exception): 'Oh here is a message with (42) numbers in parameters'\n"
" Did you mean to `re.escape()` the regex?"
)