Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better handling for exception messages with special characters #226

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
4 changes: 3 additions & 1 deletion src/hamcrest/core/core/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ def _call_function(self, function: Callable[..., Any]) -> bool:

if isinstance(self.actual, self.expected):
if self.pattern is not None:
if re.search(self.pattern, str(self.actual)) is None:
if re.search(self.pattern, str(self.actual)) is None and self.pattern != str(
self.actual
):
return False
if self.matcher is not None:
if not self.matcher.matches(self.actual):
Expand Down
15 changes: 14 additions & 1 deletion tests/hamcrest_unit_test/core/raises_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import unittest

from hamcrest import has_properties, not_
from hamcrest import has_properties, not_, assert_that
from hamcrest.core.core.raises import calling, raises
from hamcrest_unit_test.matcher_test import MatcherTest, assert_mismatch_description

Expand Down Expand Up @@ -130,6 +130,19 @@ def test_gives_correct_message_when_wrapped_with_is_not():
)


def raise_error(msg):
raise AssertionError(msg)


class ParensTest(unittest.TestCase):
def test_literal_parens(self):
message = "Message with (parens)"
assert_that(calling(raise_error).with_args(message), raises(AssertionError, message))

def test_parens_in_regex(self):
assert_that(calling(raise_error).with_args("abab"), raises(AssertionError, r"(ab)+"))


class CallingTest(unittest.TestCase):
def testCallingDoesNotImmediatelyExecuteFunction(self):
try:
Expand Down