Skip to content

Unexpected type warnings when using assert_that with sequence matchers #234

@borislubimov

Description

@borislubimov

Currently, PyCharm highlights all usages of assert_that with sequence matchers due to unexpected type warnings.
Is it possible to include an overloaded version of assert_that specifically designed for such cases?
Would something like in the example below work?

# Python 3.10.0
# pyhamcrest 2.0.4
def test_assert():
    from hamcrest import assert_that, contains_exactly
    from typing import Sequence
    from typing import TypeVar
    from hamcrest.core.matcher import Matcher
    T = TypeVar("T")

    li = [1, 2, 3]
    ls = ['1', '2', '3']
    s = '123'

    # Native hamcrest asserts

    #  Unexpected type(s): (list[int], Matcher[Sequence]) Possible type(s): (bool, str) (list[int], Matcher[list[int]])
    assert_that(li, contains_exactly(*li))
    # Unexpected type(s): (list[str], Matcher[Sequence]) Possible type(s): (bool, str) (list[str], Matcher[list[str]])
    assert_that(ls, contains_exactly(*ls))
    assert_that(ls, contains_exactly(*s))
    # Unexpected type(s): (str, Matcher[Sequence]) Possible type(s): (bool, str) (str, Matcher[str])
    assert_that(s, contains_exactly(*s))
    assert_that(s, contains_exactly(*ls))

    # Overloaded assert_that

    def my_assert_that(actual_or_assertion: Sequence[T], matcher: Matcher[Sequence[T]], reason: str = "") -> None:
        assert_that(actual_or_assertion, matcher)

    # No Warnings
    my_assert_that(li, contains_exactly(*li))
    my_assert_that(ls, contains_exactly(*ls))
    my_assert_that(s, contains_exactly(*s))
    my_assert_that(ls, contains_exactly(*s))
    my_assert_that(s, contains_exactly(*ls))

How it looks in PyCharm:

assert_that

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions