Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/170.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Add pretty string representation for matchers objects
7 changes: 7 additions & 0 deletions src/hamcrest/core/base_matcher.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from textwrap import shorten
from typing import Optional, TypeVar

from hamcrest.core.description import Description
Expand Down Expand Up @@ -25,6 +26,12 @@ class BaseMatcher(Matcher[T]):
def __str__(self) -> str:
return tostring(self)

def __repr__(self) -> str:
"""Returns matcher string representation."""
return "<{0}({1})>".format(
self.__class__.__name__, shorten(tostring(self), 60, placeholder="...")
)

def _matches(self, item: T) -> bool:
raise NotImplementedError("_matches")

Expand Down
13 changes: 13 additions & 0 deletions tests/hamcrest_unit_test/base_matcher_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ def testMismatchDescriptionShouldDescribeItem(self):
def testMatchDescriptionShouldDescribeItem(self):
assert_match_description("was <99>", PassingBaseMatcher(), 99)

def testMatcherReprShouldDescribeMatcher(self):
assert repr(FailingBaseMatcher()) == "<FailingBaseMatcher(SOME DESCRIPTION)>"

def testMatcherReprShouldTruncateLongDescription(self):
class LongDescriptionMatcher(BaseMatcher):
def describe_to(self, description):
description.append_text("1234 " * 13)

assert (
repr(LongDescriptionMatcher())
== "<LongDescriptionMatcher(1234 1234 1234 1234 1234 1234 1234 1234 1234 1234 1234...)>"
)


if __name__ == "__main__":
unittest.main()