Need help with PyHamcrest?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

581 Stars 88 Forks Other 559 Commits 20 Opened issues


Hamcrest matchers for Python

Services available


Need anything else?

Contributors list


| |docs| |status| |coverage| | |version| |downloads| |wheel| |supported-versions| |supported-implementations|

.. |docs| image:: :target: :alt: Documentation Status

.. |status| image:: :alt: CI Build Status :target:

.. |coverage| image:: :alt: Coverage Status :target:

.. |version| image:: :alt: PyPI Package latest release :target:

.. |downloads| image:: :alt: PyPI Package monthly downloads :target:

.. |wheel| image:: :alt: PyPI Wheel :target:

.. |supported-versions| image:: :alt: Supported versions :target:

.. |supported-implementations| image:: :alt: Supported implementations :target:


PyHamcrest is a framework for writing matcher objects, allowing you to declaratively define "match" rules. There are a number of situations where matchers are invaluable, such as UI validation, or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used. This tutorial shows you how to use PyHamcrest for unit testing.

When writing tests it is sometimes difficult to get the balance right between overspecifying the test (and making it brittle to changes), and not specifying enough (making the test less valuable since it continues to pass even when the thing being tested is broken). Having a tool that allows you to pick out precisely the aspect under test and describe the values it should have, to a controlled level of precision, helps greatly in writing tests that are "just right." Such tests fail when the behavior of the aspect under test deviates from the expected behavior, yet continue to pass when minor, unrelated changes to the behaviour are made.


Hamcrest can be installed using the usual Python packaging tools. It depends on distribute, but as long as you have a network connection when you install, the installation process will take care of that for you.

My first PyHamcrest test

We'll start by writing a very simple PyUnit test, but instead of using PyUnit's

method, we'll use PyHamcrest's
construct and the standard set of matchers:

.. code:: python

from hamcrest import * import unittest

class BiscuitTest(unittest.TestCase): def testEquals(self): theBiscuit = Biscuit("Ginger") myBiscuit = Biscuit("Ginger") assertthat(theBiscuit, equalto(myBiscuit))

if name == "main": unittest.main()


function is a stylized sentence for making a test assertion. In this example, the subject of the assertion is the object
, which is the first method parameter. The second method parameter is a matcher for
objects, here a matcher that checks one object is equal to another using the Python
operator. The test passes since the
class defines an

If you have more than one assertion in your test you can include an identifier for the tested value in the assertion:

.. code:: python

assertthat(theBiscuit.getChocolateChipCount(), equalto(10), "chocolate chips") assertthat(theBiscuit.getHazelnutCount(), equalto(3), "hazelnuts")

As a convenience, assert_that can also be used to verify a boolean condition:

.. code:: python

assert_that(theBiscuit.isCooked(), "cooked")

This is equivalent to the

method of unittest.TestCase, but because it's a standalone function, it offers greater flexibility in test writing.

Predefined matchers

PyHamcrest comes with a library of useful matchers:

  • Object

    • equal_to
      - match equal object
    • has_length
      - match
    • has_property
      - match value of property with given name
    • has_properties
      - match an object that has all of the given properties.
    • has_string
      - match
    • instance_of
      - match object type
    • none
      - match
      , or not
    • same_instance
      - match same object
    • calling, raises
      - wrap a method call and assert that it raises an exception
  • Number

    • close_to
      - match number close to a given value
    • greater_than
      - match numeric ordering
  • Text

    • contains_string
      - match part of a string
    • ends_with
      - match the end of a string
    • equal_to_ignoring_case
      - match the complete string but ignore case
    • equal_to_ignoring_whitespace
      - match the complete string but ignore extra whitespace
    • matches_regexp
      - match a regular expression in a string
    • starts_with
      - match the beginning of a string
    • string_contains_in_order
      - match parts of a string, in relative order
  • Logical

    • all_of
      together all matchers
    • any_of
      together all matchers
    • anything
      - match anything, useful in composite matchers when you don't care about a particular value
    • is_not
      - negate the matcher
  • Sequence

    • contains
      - exactly match the entire sequence
    • contains_inanyorder
      - match the entire sequence, but in any order
    • has_item
      - match if given item appears in the sequence
    • has_items
      - match if all given items appear in the sequence, in any order
    • is_in
      - match if item appears in the given sequence
    • only_contains
      - match if sequence's items appear in given list
    • empty
      - match if the sequence is empty
  • Dictionary

    • has_entries
      - match dictionary with list of key-value pairs
    • has_entry
      - match dictionary containing a key-value pair
    • has_key
      - match dictionary with a key
    • has_value
      - match dictionary with a value
  • Decorator

    • calling
      - wrap a callable in a deferred object, for subsequent matching on calling behaviour
    • raises
      - Ensure that a deferred callable raises as expected
    • described_as
      - give the matcher a custom failure description
    • is_
      - decorator to improve readability - see
      Syntactic sugar

The arguments for many of these matchers accept not just a matching value, but another matcher, so matchers can be composed for greater flexibility. For example,

will match any sequence where every item is less than 5.

Syntactic sugar

PyHamcrest strives to make your tests as readable as possible. For example, the

matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent:

.. code:: python

assertthat(theBiscuit, equalto(myBiscuit)) assertthat(theBiscuit, is(equalto(myBiscuit))) assertthat(theBiscuit, is_(myBiscuit))

The last form is allowed since

wraps most non-matcher arguments with
. But if the argument is a type, it is wrapped with
, so the following are also equivalent:

.. code:: python

assertthat(theBiscuit, instanceof(Biscuit)) assertthat(theBiscuit, is(instanceof(Biscuit))) assertthat(theBiscuit, is_(Biscuit))

Note that PyHamcrest's

matcher is unrelated to Python's
operator. The matcher for object identity is

Writing custom matchers

PyHamcrest comes bundled with lots of useful matchers, but you'll probably find that you need to create your own from time to time to fit your testing needs. This commonly occurs when you find a fragment of code that tests the same set of properties over and over again (and in different tests), and you want to bundle the fragment into a single assertion. By writing your own matcher you'll eliminate code duplication and make your tests more readable!

Let's write our own matcher for testing if a calendar date falls on a Saturday. This is the test we want to write:

.. code:: python

def testDateIsOnASaturday(self): d =, 4, 26) assertthat(d, is(onasaturday()))

And here's the implementation:

.. code:: python

from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod

class IsGivenDayOfWeek(BaseMatcher): def init(self, day): = day # Monday is 0, Sunday is 6

 def _matches(self, item):
     if not hasmethod(item, "weekday"):
         return False
     return item.weekday() ==

def describe_to(self, description): day_as_string = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] description.append_text("calendar date falling on ").append_text( day_as_string[] )

def onasaturday(): return IsGivenDayOfWeek(5)

For our Matcher implementation we implement the

method - which calls the
method after confirming that the argument (which may not be a date) has such a method - and the
method - which is used to produce a failure message when a test fails. Here's an example of how the failure message looks:

.. code:: python

assertthat(, 4, 6), is(onasaturday()))

fails with the message::

Expected: is calendar date falling on Saturday
     got: <2008-04-06>

Let's say this matcher is saved in a module named

. We could use it in our test by importing the factory function

.. code:: python

from hamcrest import * import unittest from isgivendayofweek import onasaturday

class DateTest(unittest.TestCase): def testDateIsOnASaturday(self): d =, 4, 26) assertthat(d, is(onasaturday()))

if name == "main": unittest.main()

Even though the

function creates a new matcher each time it is called, you should not assume this is the only usage pattern for your matcher. Therefore you should make sure your matcher is stateless, so a single instance can be reused between matches.

More resources

  • Documentation_
  • Package_
  • Sources_
  • Hamcrest_

.. _Documentation: .. _Package: .. _Sources: .. _Hamcrest:

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.