### calling and raises example Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples demonstrating the use of calling and raises for exception matching. ```python assert_that(calling(int).with_args('q'), raises(TypeError)) assert_that(calling(parse, broken_input), raises(ValueError)) assert_that( calling(valid_user, bad_json), raises(HTTPError, matching=has_properties(status_code=500)) ) ``` -------------------------------- ### Example Test Case Source: https://pyhamcrest.readthedocs.io/en/latest/custom_matchers.html An example of how to use a custom matcher in a test case. ```python def testDateIsOnASaturday(self): d = datetime.date(2008, 04, 26) assert_that(d, is_(on_a_saturday())) ``` -------------------------------- ### has_string examples Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples demonstrating the use of has_string with a starts_with matcher and a direct string value. ```python has_string(starts_with('foo')) has_string('bar') ``` -------------------------------- ### instance_of example Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Example showing how to use instance_of to check if an object is an instance of a specific type. ```python instance_of(str) ``` -------------------------------- ### has_string examples Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Examples of using has_string with a matcher and a direct value. ```python has_string(starts_with('foo')) has_string('bar') ``` -------------------------------- ### Syntactic sugar examples Source: https://pyhamcrest.readthedocs.io/en/latest/tutorial.html Demonstrates the use of the `is_` matcher for improved readability in assertions. ```python assert_that(theBiscuit, equal_to(myBiscuit)) assert_that(theBiscuit, is_(equal_to(myBiscuit))) assert_that(theBiscuit, is_(myBiscuit)) ``` ```python assert_that(theBiscuit, instance_of(Biscuit)) assert_that(theBiscuit, is_(instance_of(Biscuit))) assert_that(theBiscuit, is_(Biscuit)) ``` -------------------------------- ### has_length examples Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Examples of using has_length with a matcher and a direct value. ```python has_length(greater_than(6)) has_length(5) ``` -------------------------------- ### has_properties examples with dictionary Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples of has_properties using a dictionary to match object properties with explicit equal_to matchers or direct values. ```python has_properties({'foo':equal_to(1), 'bar':equal_to(2)}) has_properties({'foo':1, 'bar':2}) ``` -------------------------------- ### has_properties examples with keyword arguments Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples of has_properties using keyword arguments to match object properties with explicit equal_to matchers or direct values. ```python has_properties(foo=equal_to(1), bar=equal_to(2)) has_properties(foo=1, bar=2) ``` -------------------------------- ### has_length examples Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples demonstrating the use of has_length with a greater_than matcher and a direct integer value. ```python has_length(greater_than(6)) has_length(5) ``` -------------------------------- ### has_property examples Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples demonstrating the use of has_property to match a specific property with a matcher, a direct value, or without a specific value matcher. ```python has_property('name', starts_with('J')) has_property('name', 'Jon') has_property('name') ``` -------------------------------- ### Custom Matcher with describe_mismatch Source: https://pyhamcrest.readthedocs.io/en/latest/custom_matchers.html An example of implementing the `describe_mismatch` method to provide more details on assertion failure. ```python def describe_mismatch(self, item, mismatch_description): day_as_string = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] mismatch_description.append_text('got ') .append_description_of(item) .append_text(' which is a ') .append_text(day_as_string[item.weekday()]) ``` -------------------------------- ### Example of Failure Message Source: https://pyhamcrest.readthedocs.io/en/latest/custom_matchers.html Demonstrates the failure message when a custom matcher is used in an assertion that fails. ```python assert_that(datetime.date(2008, 04, 06), is_(on_a_saturday())) ``` -------------------------------- ### has_properties examples with alternating keys and values Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_library/object_matchers.html Examples of has_properties using alternating keys and values to match object properties with explicit equal_to matchers or direct values. ```python has_properties('foo', equal_to(1), 'bar', equal_to(2)) has_properties('foo', 1, 'bar', 2) ``` -------------------------------- ### Multiple Assertions with Identifiers Source: https://pyhamcrest.readthedocs.io/en/latest/tutorial.html Example of using assert_that with identifiers for tested values when there are multiple assertions. ```python assert_that(theBiscuit.getChocolateChipCount(), equal_to(10), 'chocolate chips') assert_that(theBiscuit.getHazelnutCount(), equal_to(3), 'hazelnuts') ``` -------------------------------- ### none() example Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Matches if object is `None`. -------------------------------- ### Basic PyHamcrest Test Source: https://pyhamcrest.readthedocs.io/en/latest/_sources/tutorial.rst.txt A simple PyUnit test using PyHamcrest's assert_that and equal_to matchers. ```python from hamcrest import assert_that, equal_to 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() ``` -------------------------------- ### Using Custom Matcher in a Test Module Source: https://pyhamcrest.readthedocs.io/en/latest/custom_matchers.html Shows how to import and use a custom matcher factory function in a test module. ```python 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() ``` -------------------------------- ### match_equality usage with library method Source: https://pyhamcrest.readthedocs.io/en/latest/integration.html Illustrates using match_equality with a library method that tests equality. ```python library.method_that_tests_eq(match_equality(matcher)) ``` -------------------------------- ### Asserting Exceptions Source: https://pyhamcrest.readthedocs.io/en/latest/tutorial.html Using calling and raises to test for expected exceptions, including specifying exception types and message patterns. ```python assert_that(calling(parse, bad_data), raises(ValueError)) assert_that(calling(translate).with_args(curse_words), raises(LanguageError, "\w+very naughty")) assert_that(broken_function, raises(Exception)) # This will fail and complain that 23 is not callable # assert_that(23, raises(IOError)) ``` -------------------------------- ### Asserting Exceptions from Async Methods (Sync Test Runner) Source: https://pyhamcrest.readthedocs.io/en/latest/tutorial.html Testing exceptions from async methods using resolved and future_raising with a synchronous test runner by manually running the event loop. ```python class Test(unittest.TestCase): def test_parse(self): async def test(): future = parse("some bad data") assert_that(await resolved(future), future_raising(ValueError)) asyncio.get_event_loop().run_until_complete(test()) ``` -------------------------------- ### match_equality usage with equality operator Source: https://pyhamcrest.readthedocs.io/en/latest/integration.html Shows how match_equality can wrap a matcher to define equality, allowing its use with the equality operator. ```python assert match_equality(matcher) == object ``` -------------------------------- ### calling wrapper for function calls Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Demonstrates how to use the `calling` function to wrap a function call for delayed execution, allowing the `raises` matcher to catch exceptions. It shows how to provide arguments using `with_args`. ```python calling(my_method).with_args(arguments, and_='keywords') ``` -------------------------------- ### assert_that with boolean condition Source: https://pyhamcrest.readthedocs.io/en/latest/integration.html Demonstrates how assert_that can be used to verify a boolean condition, similar to unittest.TestCase.assertTrue. ```python hamcrest.core.assert_that.assert_that(_assertion_[, _reason_]) ``` -------------------------------- ### Asserting Exceptions from Async Methods (Async Test Runner) Source: https://pyhamcrest.readthedocs.io/en/latest/tutorial.html Testing exceptions from async methods using resolved and future_raising with an async test runner like IsolatedAsyncioTestCase. ```python async def parse(input: str): ... class Test(unittest.IsolatedAsyncioTestCase): async def testParse(self): future = parse("some bad data") assert_that(await resolved(future), future_raising(ValueError)) ``` -------------------------------- ### Asserting a Boolean Condition Source: https://pyhamcrest.readthedocs.io/en/latest/tutorial.html Using assert_that to verify a boolean condition, similar to unittest.TestCase's assert_ method. ```python assert_that(theBiscuit.isCooked(), 'cooked') ``` -------------------------------- ### Custom Matcher Implementation Source: https://pyhamcrest.readthedocs.io/en/latest/custom_matchers.html The implementation of a custom matcher for checking if a date falls on a Saturday. ```python 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) ``` -------------------------------- ### IsSequenceContainingEvery Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that checks if all provided matchers are satisfied by elements in the sequence. It attempts to establish a one-to-one correspondence between elements and matchers. Non-matcher arguments are implicitly wrapped in equal_to. ```python class hamcrest.library.collection.issequence_containing.IsSequenceContainingEvery(* element_matchers) Bases: BaseMatcher[Sequence[T]] Parameters: element_matchers (Matcher[T]): ``` -------------------------------- ### is_in Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Function to create an IsIn matcher, which checks if an object is a member of a specified sequence. ```python hamcrest.library.isin.is_in(sequence) Matches if evaluated object is present in a given sequence. Parameters: sequence (Sequence[T]): The sequence to search. Return type: Matcher[T] ``` -------------------------------- ### IsSequenceContaining Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that iterates through a sequence, checking if each element satisfies any of the provided matchers in order. Elements are matched one-to-one with matchers. Non-matcher arguments are wrapped in equal_to. ```python class hamcrest.library.collection.issequence_containing.IsSequenceContaining(element_matcher) Bases: BaseMatcher[Sequence[T]] Parameters: element_matcher (Matcher[T]): ``` -------------------------------- ### has_items Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that verifies if all provided matchers are satisfied by elements within the sequence. It searches for elements in the sequence that satisfy each given matcher. Non-matcher arguments are implicitly wrapped in equal_to. ```python hamcrest.library.collection.issequence_containing.has_items(* items) Matches if all of the given matchers are satisfied by any elements of the sequence. Parameters: match1,... items (Union[Matcher[T], T]): Return type: Matcher[Sequence[T]] ``` -------------------------------- ### has_property with only name Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Matches if object has a property with a given name. If the `match` argument is not provided, the `anything` matcher is used so that `has_property` is satisfied if a matching property is found. ```python has_property('name') ``` -------------------------------- ### has_property with matcher Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Matches if object has a property with a given name whose value satisfies a given matcher. If the `match` argument is not provided, the `anything` matcher is used. ```python has_property('name', starts_with('J')) ``` -------------------------------- ### has_property with expected value Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/object_matchers.html Matches if object has a property with a given name whose value satisfies a given matcher. If the `match` argument is not a matcher, it is implicitly wrapped in an `equal_to` matcher. ```python has_property('name', 'Jon') ``` -------------------------------- ### IsSequenceOnlyContaining Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that checks if every element in a sequence satisfies a given matcher. ```python class hamcrest.library.issequence_onlycontaining.IsSequenceOnlyContaining(matcher) Bases: BaseMatcher[Sequence[T]] Parameters: matcher (Matcher[T]): ``` -------------------------------- ### contains_exactly Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matches if sequence’s elements satisfy a given list of matchers, in order. This matcher iterates the evaluated sequence and a given list of matchers, seeing if each element satisfies its corresponding matcher. Any argument that is not a matcher is implicitly wrapped in an `equal_to` matcher to check for equality. ```python hamcrest.library.collection.issequence_containinginorder.contains_exactly(_* items_) ``` -------------------------------- ### has_item Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that checks if any element in a sequence satisfies a given matcher. If the argument is not a matcher, it's wrapped in equal_to. ```python hamcrest.library.collection.issequence_containing.has_item(match) Matches if any element of sequence satisfies a given matcher. Parameters: match (Union[Matcher[T], T]): The matcher to satisfy, or an expected value for `equal_to` matching. Return type: Matcher[Sequence[T]] ``` -------------------------------- ### contains Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Deprecated - use contains_exactly(*items) ```python hamcrest.library.collection.issequence_containinginorder.contains(_* items_) ``` -------------------------------- ### only_contains Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that verifies if each element of a sequence satisfies any of the provided matchers. ```python hamcrest.library.issequence_onlycontaining.only_contains(* items) Matches if each element of sequence satisfies any of the given matchers. Parameters: ``` -------------------------------- ### IsIn Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matcher that checks if the evaluated object is present within a given sequence using the 'in' membership operator. ```python class hamcrest.library.isin.IsIn(sequence) Bases: BaseMatcher[T] Parameters: sequence (Sequence[T]): ``` -------------------------------- ### contains_inanyorder Source: https://pyhamcrest.readthedocs.io/en/latest/matcher_internals/sequence_matchers.html Matches if sequences’s elements, in any order, satisfy a given list of matchers. ```python hamcrest.library.collection.issequence_containinginanyorder.contains_inanyorder(_* items_) ```