Skip to content
Open
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
14 changes: 8 additions & 6 deletions src/hamcrest/core/core/described_as.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import re
from typing import Any, Optional, Tuple
from typing import Optional, Tuple, TypeVar

from hamcrest.core.base_matcher import BaseMatcher
from hamcrest.core.description import Description
Expand All @@ -11,19 +11,21 @@

ARG_PATTERN = re.compile("%([0-9]+)")

T = TypeVar("T")

class DescribedAs(BaseMatcher[Any]):

class DescribedAs(BaseMatcher[T]):
def __init__(
self, description_template: str, matcher: Matcher[Any], *values: Tuple[Any, ...]
self, description_template: str, matcher: Matcher[T], *values: Tuple[T, ...]
) -> None:
self.template = description_template
self.matcher = matcher
self.values = values

def matches(self, item: Any, mismatch_description: Optional[Description] = None) -> bool:
def matches(self, item: T, mismatch_description: Optional[Description] = None) -> bool:
return self.matcher.matches(item, mismatch_description)

def describe_mismatch(self, item: Any, mismatch_description: Description) -> None:
def describe_mismatch(self, item: T, mismatch_description: Description) -> None:
self.matcher.describe_mismatch(item, mismatch_description)

def describe_to(self, description: Description) -> None:
Expand All @@ -38,7 +40,7 @@ def describe_to(self, description: Description) -> None:
description.append_text(self.template[text_start:])


def described_as(description: str, matcher: Matcher[Any], *values) -> Matcher[Any]:
def described_as(description: str, matcher: Matcher[T], *values) -> Matcher[T]:
"""Adds custom failure description to a given matcher.

:param description: Overrides the matcher's description.
Expand Down
7 changes: 7 additions & 0 deletions tests/type-hinting/core/core/test_described_as.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
- case: described_as
# pypy + mypy doesn't work. See https://foss.heptapod.net/pypy/pypy/-/issues/3526
skip: platform.python_implementation() == "PyPy"
main: |
from hamcrest import is_, described_as

reveal_type(described_as("oh, hi", is_(98))) # N: Revealed type is "hamcrest.core.matcher.Matcher[builtins.int]"