PyHamcrest
PyHamcrest is a framework for writing matcher objects for Python. It provides a declarative way to define 'match' rules, most commonly used in unit testing to create flexible and precise assertions. It is currently at version 2.1.0 and has a consistent release cadence with several minor and major updates over the years, most recently adding features for async futures.
Warnings
- breaking PyHamcrest dropped formal support for Python 2.x (all versions) and Python 3.x versions older than 3.4 starting with V1.9.0. Attempting to install or run V1.9.0 or later on unsupported Python versions will result in errors.
- breaking In V2.0.0, the `assert_that` function's behavior changed. If a non-boolean value was passed as the matcher argument, it now implicitly wraps it with `equal_to()`. Previously, this might have behaved differently or raised an error depending on the exact context.
- deprecated The `numpy alias` was deprecated in PyHamcrest V2.1.0. While it might still function, its use is discouraged and will be removed in future versions.
- gotcha When using the `raises()` matcher (e.g., for asserting exceptions) with `pytest`, you must wrap the callable in `calling()` for it to work correctly. Directly passing the callable to `assert_that(callable, raises(Exception))` will fail.
- gotcha Custom matchers should generally be stateless. If you create a custom matcher and intend to reuse a single instance across multiple assertions, ensure that its internal state does not change during the matching process, as this can lead to unexpected test results.
Install
-
pip install pyhamcrest
Imports
- assert_that
from hamcrest import assert_that, equal_to
- anything
from hamcrest import anything
- contains_string
from hamcrest import contains_string
- *
from hamcrest import *
Quickstart
from hamcrest import assert_that, equal_to, greater_than
class MyObject:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if not isinstance(other, MyObject):
return NotImplemented
return self.value == other.value
def test_object_equality():
obj1 = MyObject('test')
obj2 = MyObject('test')
assert_that(obj1, equal_to(obj2))
print('Test object_equality passed.')
def test_number_comparison():
number = 10
assert_that(number, greater_than(5))
print('Test number_comparison passed.')
if __name__ == '__main__':
test_object_equality()
test_number_comparison()