Registry / testing / pyhamcrest

pyhamcrest

JSON →
library2.1.0pypypi✓ verified 26d ago

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.

pip install pyhamcrest
INSTALL
IMPORT
SIG · PYHAMCREST
P
pyhamcrest
testingpythonv2.1.0
Install
1.6s avg
Import
426ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.456s · 18.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.396s · 19MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

assert_that
from hamcrest import assert_that, equal_to
anything
from hamcrest import anything
contains_string
from hamcrest import contains_string
*
from hamcrest import *
Wildcard import is common in tests for brevity but can lead to name collisions.

This quickstart demonstrates basic usage of `assert_that` with `equal_to` for object comparison and `greater_than` for numeric comparison. PyHamcrest matchers provide a more readable and flexible way to express assertions in tests.

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()
Debug
Known issues
breakingPyHamcrest 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.
fix
Upgrade to Python 3.6+ or pin PyHamcrest to version <1.9.0 for older Python environments.
affects: >=1.9.0
breakingIn 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.
fix
Explicitly use `equal_to()` for value comparisons (e.g., `assert_that(actual, equal_to(expected))` instead of `assert_that(actual, expected)`) to ensure consistent behavior across versions.
affects: >=2.0.0
deprecatedThe `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.
fix
Avoid using the `numpy alias`. If your code depends on specific NumPy-related matchers, ensure you are using the correct, explicit imports and patterns as per current documentation.
affects: 2.1.0
gotchaWhen 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.
fix
Use `assert_that(calling(your_function), raises(YourException))`.
affects: All versions
gotchaCustom 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.
fix
Design custom matchers to be immutable and stateless, or create new instances for each assertion if state management is unavoidable.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'hamcrest'
The `pyhamcrest` library is either not installed, or matchers are being imported from the top-level `hamcrest` package incorrectly without specifying the `hamcrest.library` submodule or individual matchers.
fix
Ensure `pyhamcrest` is installed via `pip install PyHamcrest` and import matchers explicitly or using a wildcard from `hamcrest` like `from hamcrest import assert_that, equal_to` or `from hamcrest.library.object import equal_to`.
NameError: name 'is_' is not defined
Common matchers like `is_`, `equal_to`, `has_item`, etc., are not automatically available. They must be explicitly imported from the `hamcrest` package.
fix
Import the specific matchers you need, for example: `from hamcrest import assert_that, is_, equal_to` or `from hamcrest import *` to import all top-level matchers.
Pytest fails when using pyhamcrest raises
When using `pytest`, the `raises` matcher from `pyhamcrest` for asserting exceptions might not behave as expected or integrate directly with `pytest`'s own exception handling context manager `pytest.raises` without careful composition, often resulting in `AssertionError` from the matcher itself rather than a `pytest`-native pass/fail.
fix
For asserting exceptions within `pytest` tests, it's generally recommended to use `pytest.raises` as a context manager: `with pytest.raises(SomeException): your_function_that_raises()` or use PyHamcrest's `calling` matcher with `raises` for more flexible checks: `assert_that(calling(your_function).with_args(arg1), raises(SomeException))`.
pyhamcrest contains matcher not working for list of items (expected specific item, got AssertionError)
The `contains` matcher in PyHamcrest expects a sequence of matchers, one for each item in the *exact order* of the expected sequence. It does not check if *any* of the items are present in a sequence. If you want to check for the presence of specific items in a sequence (regardless of order or other items), you should use `has_item` or `has_items`.
fix
If you want to assert that a sequence contains specific items, use `has_item` or `has_items`: `assert_that(my_list, has_item(expected_item))` or `assert_that(my_list, has_items(item1, item2))`.
Upgrade
Version history
2.1.0latest on PyPI · released Oct 22, 2023
Audit
Dependencies
PythonrequiredRequires Python 3.6 or newer.
Agent activity
7 hits · last 30 days
node
6
Resources
pyhamcrest — pip install pyhamcrest · libregistry