Skip to main content

Hamcrest framework for matcher objects

Project description

Introduction

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.

Installation

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 assertEqual method, we’ll use PyHamcrest’s assert_that construct and the standard set of matchers:

from hamcrest import *
import unittest

class BiscuitTest(unittest.TestCase):
    def testEquals(self):
        theBiscuit = Biscuit('Ginger')
        myBiscuit = Biscuit('Ginger')
        assert_that(theBiscuit, equal_to(myBiscuit))

if __name__ == '__main__':
    unittest.main()

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

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

assert_that(theBiscuit.getChocolateChipCount(), equal_to(10), 'chocolate chips')
assert_that(theBiscuit.getHazelnutCount(), equal_to(3), 'hazelnuts')

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

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

This is equivalent to the assert_ method of unittest.TestCase, but because it’s a standalone function, it offers greater flexibility in test writing.

A tour of common matchers

PyHamcrest comes with a library of useful matchers:

  • Core

    • anything - always matches, useful if you don’t care what the object under test is

    • described_as - decorator to add custom failure description

    • is_ - decorator to improve readability - see Syntactic sugar, below

  • Logical

    • all_of - matches if all matchers match, short circuits (like Python and)

    • any_of - matches if any matchers match, short circuits (like Python or)

    • is_not - matches if the wrapped matcher doesn’t match and vice versa

  • Object

    • equal_to - tests object equality using ==

    • has_length - tests whether len(item) satisfies a given matcher

    • has_string - tests whether str(item) satisfies another matcher

    • instance_of - tests type

    • none, not_none - tests for None

    • same_instance - tests object identity

  • Collection

    • has_entry, has_entries, has_key, has_value - tests that a dictionary contains an entry, key or value

    • has_item, contains, contains_inanyorder, only_contains - tests that a sequence contains elements

  • Number

    • close_to - tests that numeric values are close to a given value

    • greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to - tests ordering

  • Text

    • equal_to_ignoring_case - tests string equality ignoring case

    • equal_to_ignoring_whitespace - test strings equality ignoring differences in runs of whitespace

    • contains_string, ends_with, starts_with, string_contains_in_order - tests string matching

Syntactic sugar

PyHamcrest strives to make your tests as readable as possible. For example, the is_ matcher is a wrapper that doesn’t add any extra behavior to the underlying matcher. The following assertions are all equivalent:

assert_that(theBiscuit, equal_to(myBiscuit))
assert_that(theBiscuit, is_(equal_to(myBiscuit)))
assert_that(theBiscuit, is_(myBiscuit))

The last form is allowed since is_(value) wraps most non-matcher arguments with equal_to. But if the argument is a type, it is wrapped with instance_of, so the following are also equivalent:

assert_that(theBiscuit, instance_of(Biscuit))
assert_that(theBiscuit, is_(instance_of(Biscuit)))
assert_that(theBiscuit, is_(Biscuit))

Note that PyHamcrest’s ``is_`` matcher is unrelated to Python’s ``is`` operator. The matcher for object identity is ``same_instance``.

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:

def testDateIsOnASaturday(self):
    d = datetime.date(2008, 04, 26)
    assert_that(d, is_(on_a_saturday()))

And here’s the implementation:

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

class IsGivenDayOfWeek(BaseMatcher):

    def __init__(self, day):
        self.day = day  # Monday is 0, Sunday is 6

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

    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[self.day])

def on_a_saturday():
    return IsGivenDayOfWeek(5)

For our Matcher implementation we implement the _matches method - which calls the weekday method after confirming that the argument (which may not be a date) has such a method - and the describe_to method - which is used to produce a failure message when a test fails. Here’s an example of how the failure message looks:

assert_that(datetime.date(2008, 04, 06), is_(on_a_saturday()))

fails with the message:

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

Let’s say this matcher is saved in a module named isgivendayofweek. We could use it in our test by importing the factory function on_a_saturday:

from hamcrest import *
import unittest
from isgivendayofweek import on_a_saturday

class DateTest(unittest.TestCase):
    def testDateIsOnASaturday(self):
        d = datetime.date(2008, 04, 26)
        assert_that(d, is_(on_a_saturday()))

if __name__ == '__main__':
    unittest.main()

Even though the on_a_saturday 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

PyHamcrest-1.5.tar.gz (34.0 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

PyHamcrest-1.5-py3.2.egg (167.3 kB view details)

Uploaded Egg

PyHamcrest-1.5-py3.1.egg (167.3 kB view details)

Uploaded Egg

PyHamcrest-1.5-py2.7.egg (171.7 kB view details)

Uploaded Egg

PyHamcrest-1.5-py2.6.egg (170.8 kB view details)

Uploaded Egg

PyHamcrest-1.5-py2.5.egg (171.6 kB view details)

Uploaded Egg

File details

Details for the file PyHamcrest-1.5.tar.gz.

File metadata

  • Download URL: PyHamcrest-1.5.tar.gz
  • Upload date:
  • Size: 34.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyHamcrest-1.5.tar.gz
Algorithm Hash digest
SHA256 7c1d7450581e1d80c59c2e83eac0d58c976d94312009885f2a444ac13bfe66a8
MD5 65b125a831ec677dfc62e69b7105380d
BLAKE2b-256 f8e7a552bdd2bb1a82a0739b3c94d487ce2d6849380e6f7742064cb7379b4f32

See more details on using hashes here.

File details

Details for the file PyHamcrest-1.5-py3.2.egg.

File metadata

  • Download URL: PyHamcrest-1.5-py3.2.egg
  • Upload date:
  • Size: 167.3 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyHamcrest-1.5-py3.2.egg
Algorithm Hash digest
SHA256 271430a3d1c7ffdab048326aee831cbb5cf5859d2962751c68d6c0eaa8b14c48
MD5 9a2d5ec5431d69e8f6f15a02b367e530
BLAKE2b-256 7ead50e42b142b9589195f0eb154bc9d7fb484cc0ce9e4e9b50503e50c4b11df

See more details on using hashes here.

File details

Details for the file PyHamcrest-1.5-py3.1.egg.

File metadata

  • Download URL: PyHamcrest-1.5-py3.1.egg
  • Upload date:
  • Size: 167.3 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyHamcrest-1.5-py3.1.egg
Algorithm Hash digest
SHA256 74b02ea39eb5a5f06e59d969d731cace59d9254b6c6f44dadfdb1bda2224ea8b
MD5 94549d8da1b3da4acda8fbec018d207b
BLAKE2b-256 f96f54e66f547430afff95c7a3fe8207184c02b406ab939451bf572ba4efd3f7

See more details on using hashes here.

File details

Details for the file PyHamcrest-1.5-py2.7.egg.

File metadata

  • Download URL: PyHamcrest-1.5-py2.7.egg
  • Upload date:
  • Size: 171.7 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyHamcrest-1.5-py2.7.egg
Algorithm Hash digest
SHA256 871ae81a729821e9820116d420ed81054891c12c144381f45499a73b65cbb39f
MD5 91220833988f1ce533662f7226e6cd9c
BLAKE2b-256 35cfb5d59bf8cd2f0bee43ca4ffe2dce1fdf1ae37cb888978c3d6be3e3d0f12f

See more details on using hashes here.

File details

Details for the file PyHamcrest-1.5-py2.6.egg.

File metadata

  • Download URL: PyHamcrest-1.5-py2.6.egg
  • Upload date:
  • Size: 170.8 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyHamcrest-1.5-py2.6.egg
Algorithm Hash digest
SHA256 baffc8ce81dfc2d202f7e4791d394b4d27df8dd9c8ab24e6b6e534455e8d8d9c
MD5 2a1fb8fd10dd7c4128bf5ebade2a1486
BLAKE2b-256 dd2c9174b4dbc20e7e8a4eb5e7974e25250c5b228ac8d25b16071f30ad863e06

See more details on using hashes here.

File details

Details for the file PyHamcrest-1.5-py2.5.egg.

File metadata

  • Download URL: PyHamcrest-1.5-py2.5.egg
  • Upload date:
  • Size: 171.6 kB
  • Tags: Egg
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for PyHamcrest-1.5-py2.5.egg
Algorithm Hash digest
SHA256 5e06540fe2e67821450adb2e48ccfc5e14a5c24a6fd016ce160f3c1ecf9d92c7
MD5 3ae06443a58dd85ac8db98b7616cdce1
BLAKE2b-256 f7af59e401ef1422ae1e73490400b20e896ef0eca5e8c04be142e4a23b61b210

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page