PyHamcrest

2.1.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

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()

view raw JSON →