diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index fd38b950c..3095dd37e 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -633,17 +633,18 @@ class ExceptionInfo(Generic[_E]): ) return fmt.repr_excinfo(self) - def match(self, regexp: "Union[str, Pattern]") -> bool: + def match(self, regexp: "Union[str, Pattern]") -> "Literal[True]": """ - Check whether the regular expression 'regexp' is found in the string - representation of the exception using ``re.search``. If it matches - then True is returned (so that it is possible to write - ``assert excinfo.match()``). If it doesn't match an AssertionError is - raised. + Check whether the regular expression `regexp` matches the string + representation of the exception using :func:`python:re.search`. + If it matches `True` is returned. + If it doesn't match an `AssertionError` is raised. """ __tracebackhide__ = True - if not re.search(regexp, str(self.value)): - assert 0, "Pattern {!r} not found in {!r}".format(regexp, str(self.value)) + assert re.search( + regexp, str(self.value) + ), "Pattern {!r} does not match {!r}".format(regexp, str(self.value)) + # Return True to allow for "assert excinfo.match()". return True diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index c67201191..412f11edc 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -411,13 +411,15 @@ def test_match_raises_error(testdir): ) result = testdir.runpytest() assert result.ret != 0 - result.stdout.fnmatch_lines(["*AssertionError*Pattern*[123]*not found*"]) + + exc_msg = "Pattern '[[]123[]]+' does not match 'division by zero'" + result.stdout.fnmatch_lines(["E * AssertionError: {}".format(exc_msg)]) result.stdout.no_fnmatch_line("*__tracebackhide__ = True*") result = testdir.runpytest("--fulltrace") assert result.ret != 0 result.stdout.fnmatch_lines( - ["*__tracebackhide__ = True*", "*AssertionError*Pattern*[123]*not found*"] + ["*__tracebackhide__ = True*", "E * AssertionError: {}".format(exc_msg)] ) diff --git a/testing/python/raises.py b/testing/python/raises.py index cfdbe6748..a53b2137a 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -194,7 +194,7 @@ class TestRaises: int("asdf") msg = "with base 16" - expr = r"Pattern '{}' not found in \"invalid literal for int\(\) with base 10: 'asdf'\"".format( + expr = r"Pattern '{}' does not match \"invalid literal for int\(\) with base 10: 'asdf'\"".format( msg ) with pytest.raises(AssertionError, match=expr): @@ -206,7 +206,7 @@ class TestRaises: with pytest.raises(AssertionError, match="'foo"): raise AssertionError("'bar") (msg,) = excinfo.value.args - assert msg == 'Pattern "\'foo" not found in "\'bar"' + assert msg == 'Pattern "\'foo" does not match "\'bar"' def test_raises_match_wrong_type(self): """Raising an exception with the wrong type and match= given.