pax_global_header00006660000000000000000000000064126666613640014532gustar00rootroot0000000000000052 comment=00d6e49461e919b8a4a9a7679b6c99beabbe873e PyHamcrest-1.9.0/000077500000000000000000000000001266666136400136205ustar00rootroot00000000000000PyHamcrest-1.9.0/.coveragerc000066400000000000000000000000301266666136400157320ustar00rootroot00000000000000[run] source = hamcrest PyHamcrest-1.9.0/.gitignore000066400000000000000000000000671266666136400156130ustar00rootroot00000000000000.DS_Store *.pyc PyHamcrest.egg-info/ build/ dist/ .tox PyHamcrest-1.9.0/.travis.yml000066400000000000000000000006371266666136400157370ustar00rootroot00000000000000language: python python: - 2.7 env: - TOX_ENV=py33 - TOX_ENV=py33-numpy - TOX_ENV=py32 - TOX_ENV=py27 - TOX_ENV=py27-numpy - TOX_ENV=py26 - TOX_ENV=pypy - TOX_ENV=docs-py3 before_install: - export EASY_SETUP_URL='http://peak.telecommunity.com/dist/ez_setup.py' install: - pip install --use-mirrors tox coveralls "virtualenv<14.0" script: - tox -e $TOX_ENV after_success: - coveralls PyHamcrest-1.9.0/CHANGES.txt000066400000000000000000000142501266666136400154330ustar00rootroot00000000000000=== Version 1.9.0 == Drop formal support for 2.x < 2.7 Drop formal support for 3.x < 3.4 Fix #62 - Return result of a deferred call === Version 1.8.5 === Fix #56 - incorrect handling of () in is_ matcher Fix #60 - correct calling API call with args === Version 1.8.4 == * Fix #54 - Make instance_of work with tuple like isinstance and unittest's assertIsInstance === Version 1.8.3 === * Fix #52 - bad handling when reporting mismatches for byte arrays in Python 3 === Version 1.8.2 === * [Bug] Fix unicode syntax via u() introduction (puppsman) === Version 1.8.1 === * Added not_ alias for is_not [Matteo Bertini] * Added doc directory to the sdist [Alex Brandt] === Version 1.8 == * Supported versions - Support for Python 2.5 and Jython 2.5 has been dropped. They may still work, but no promises. * Bug Fixes - [#39] is_empty was missing from the global namespace * New Features - Support for numpy numeric values in iscloseto (Alexander Beedie) - A matcher targeting exceptions and call results (Per Fagrell) === Version 1.7 == 2 Sep 2013 (Version 1.7.2) * Supported versions - As of this version, support for Python 3.1 has been dropped due to no available CI platform. - Added support for Python 3.3 * Bug fixes: - string_contains_in_order is now used in the test as it would be in an application, and is properly exported. (Romilly Cocking) - Fix mismatch description of containing_inanyorder (David Keijser) - added import of stringmatches to text/__init__.py (Eric Scheidemantle) - added matches_regexp to __all__ list to library/__init__.py (Eric Scheidemantle) 5 Jan 2010 (Version 1.7.1) * Bug fixes: - included a fix by jaimegildesagredo for issue #28 (has_properties was not importable) - included a fix by keys for contains_inanyorder 29 Dec 2012 (All changes by Chris Rose unless otherwise noted.) * New matchers: - matches_regexp matches a regular expression in a string. - has_properties matches an object with more than one property. - is_empty matches any object with length 0. * Improvements: - Can now do matching against old-style classes. - Sequence matchers handle generators, as well as actual sequences and pseudo-sequences. - README enhancements by ming13 === Version 1.6 == 27 Sep 2011 (All changes by Chris Rose unless otherwise noted.) * Packaging: - Python 3.2 support. * New matchers: - has_property('property_name', value_matcher) matches if object has a property with a given name whose value satisfies a given matcher. * Improvements: - hasEntries supports two new calling conventions: has_entries({'key' : value_matcher, 'key_2' : other_value_matcher}) has_entries(key=value_matcher, key_2=other_value_matcher) - Describe Unicode strings by their __repr__. Thanks to: Sebastian Arming - Rewrote documentation. (Jon Reid) == Version 1.5 == 29 Apr 2011 * Packaging: - Python 3.1 support. Thanks to: Chris Rose - Easier installation with bootstrapping. Thanks to: Chris Rose * Mock integration: - "match_equality" wraps a matcher to define equality in terms of satisfying the matcher. This allows Hamcrest matchers to be used in libraries that are not Hamcrest-aware, such as Michael Foord's mock library. Thanks to: Chris Rose * New matcher: - "string_contains_in_order" matches string containing given list of substrings, in order. Thanks to: Romilly Cocking * Improved matchers: - For consistency, changed "any_of" and "all_of" to implicitly wrap non-matcher values in EqualTo. Thanks to: Chris Rose - Changed "sameInstance" mismatch description to omit address when describing None. == Version 1.4 == 13 Feb 2011 * New matchers: - "has_entries" matches dictionary containing key-value pairs satisfying a given list of alternating keys and value matchers. * "assert_that" can be invoked with a single boolean argument; the reason message is now optional. This is a convenience replacement for assertTrue. Thanks to: Jeong-Min Lee * Improved descriptions: - Reverted 1.3 change: Describe None as "" after all, since it is an object. - "is_" no longer says "is ..." in its description, but just lets the inner description pass through. - Consistently use articles to begin descriptions, such as "a sequence containing" instead of "sequence containing". == Version 1.3 == 04 Feb 2011 * PyHamcrest is now compatible with Python 3! To install PyHamcrest on Python 3: - Install the "distribute" package, http://pypi.python.org/pypi/distribute - Run "python3 setup.py install" Unit tests are not converted by the install procedure. Run "2to3 -nw ." separately to convert them. You may discover import statements in the __init__.py files (and one in core/base_description.py) that need dot prefixes. Thanks to: Jeong-Min Lee * Improved descriptions and mismatch descriptions of several matchers, including: - Fixed "contains" and "contains_inanyorder" to describe mismatch if item is not a sequence. - Fixed "described_as" to use nested matcher to generate mismatch description. - "same_instance" is more readable, and includes object memory addresses. - If object has a length, "has_length" mismatch describes actual length. - Describe None as "None" instead of "". - Don't wrap angle brackets around a description that already has them. - Improved readability of several matchers. == Version 1.2.1 == 04 Jan 2011 * Fixed "assert_that" to describe the diagnosis of the mismatch, not just the mismatched value. PyHamcrest will now give even more useful information. * Expanded BaseDescription.append_description_of to handle all types of values, not just self-describing values. * Deprecated: - Description.append_value no longer needed; call append_description_of instead. - BaseDescription.append_value_list no longer needed; call append_list instead. - SelfDescribingValue no longer needed. 1.2.1 fixes to 1.2: - Corrected manifest so install works. Thanks to: Jeong-Min Lee == Version 1.1 == 28 Dec 2010 * New matchers: - "contains" matches sequence containing matching items in order. - "contains_inanyorder" matches sequence containing matching items in any order. * Added Sphinx documentation support. == Version 1.0 == 04 Dec 2010 * First official release * Text matchers now support Unicode strings 15 Jan 2008 * Initial submission PyHamcrest-1.9.0/LICENSE.txt000066400000000000000000000026741266666136400154540ustar00rootroot00000000000000BSD License Copyright 2011 hamcrest.org All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Hamcrest nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PyHamcrest-1.9.0/MANIFEST.in000066400000000000000000000001621266666136400153550ustar00rootroot00000000000000include CHANGES.txt include LICENSE.txt include README.md recursive-include examples *.py recursive-include doc * PyHamcrest-1.9.0/README.rst000066400000000000000000000273031266666136400153140ustar00rootroot00000000000000PyHamcrest ========== | |docs| |travis| |coveralls| |landscape| |scrutinizer| |codeclimate| | |version| |downloads| |wheel| |supported-versions| |supported-implementations| .. |docs| image:: https://readthedocs.org/projects/pyhamcrest/badge/?style=flat :target: https://pyhamcrest.readthedocs.org/ :alt: Documentation Status .. |travis| image:: http://img.shields.io/travis/hamcrest/PyHamcrest/master.png?style=flat :alt: Travis-CI Build Status :target: https://travis-ci.org/hamcrest/PyHamcrest .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/hamcrest/PyHamcrest?branch=master :alt: AppVeyor Build Status :target: https://ci.appveyor.com/project/hamcrest/PyHamcrest .. |coveralls| image:: http://img.shields.io/coveralls/hamcrest/PyHamcrest/master.png?style=flat :alt: Coverage Status :target: https://coveralls.io/r/hamcrest/PyHamcrest .. |landscape| image:: https://landscape.io/github/hamcrest/PyHamcrest/master/landscape.svg?style=flat :target: https://landscape.io/github/hamcrest/PyHamcrest/master :alt: Code Quality Status .. |codeclimate| image:: https://codeclimate.com/github/hamcrest/PyHamcrest/badges/gpa.svg :target: https://codeclimate.com/github/hamcrest/PyHamcrest :alt: Code Climate .. |version| image:: http://img.shields.io/pypi/v/PyHamcrest.png?style=flat :alt: PyPI Package latest release :target: https://pypi.python.org/pypi/PyHamcrest .. |downloads| image:: http://img.shields.io/pypi/dm/PyHamcrest.png?style=flat :alt: PyPI Package monthly downloads :target: https://pypi.python.org/pypi/PyHamcrest .. |wheel| image:: https://pypip.in/wheel/PyHamcrest/badge.png?style=flat :alt: PyPI Wheel :target: https://pypi.python.org/pypi/PyHamcrest .. |supported-versions| image:: https://pypip.in/py_versions/PyHamcrest/badge.png?style=flat :alt: Supported versions :target: https://pypi.python.org/pypi/PyHamcrest .. |supported-implementations| image:: https://pypip.in/implementation/PyHamcrest/badge.png?style=flat :alt: Supported imlementations :target: https://pypi.python.org/pypi/PyHamcrest .. |scrutinizer| image:: https://img.shields.io/scrutinizer/g/hamcrest/PyHamcrest/master.png?style=flat :alt: Scrtinizer Status :target: https://scrutinizer-ci.com/g/hamcrest/PyHamcrest/ 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: .. code:: python 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: .. code:: python 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: .. code:: python 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. Predefined matchers =================== PyHamcrest comes with a library of useful matchers: * Object * ``equal_to`` - match equal object * ``has_length`` - match ``len()`` * ``has_property`` - match value of property with given name * ``has_properties`` - match an object that has all of the given properties. * ``has_string`` - match ``str()`` * ``instance_of`` - match object type * ``none``, ``not_none`` - match ``None``, or not ``None`` * ``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``, ``greater_than_or_equal_to``, ``less_than``, ``less_than_or_equal_to`` - 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`` - ``and`` together all matchers * ``any_of`` - ``or`` 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 deffered 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` below 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, ``only_contains(less_than(5))`` 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 ``is_`` matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent: .. code:: python 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: .. code:: python 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: .. code:: python def testDateIsOnASaturday(self): d = datetime.date(2008, 04, 26) assert_that(d, is_(on_a_saturday())) 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): 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: .. code:: python 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``: .. code:: 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() 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. More resources ============== * Documentation_ * Package_ * Sources_ * Hamcrest_ .. _Documentation: http://readthedocs.org/docs/pyhamcrest/en/V1.8.2/ .. _Package: http://pypi.python.org/pypi/PyHamcrest .. _Sources: https://github.com/hamcrest/PyHamcrest .. _Hamcrest: http://hamcrest.org PyHamcrest-1.9.0/devel-requirements.txt000066400000000000000000000000541266666136400202000ustar00rootroot00000000000000six>=1.4 tox>=1.8 pytest>=2.6 Sphinx>=1.2.2 PyHamcrest-1.9.0/distribute_setup.py000066400000000000000000000366151266666136400176030ustar00rootroot00000000000000#!python """Bootstrap distribute installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from distribute_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import sys import time import fnmatch import tempfile import tarfile from distutils import log try: from site import USER_SITE except ImportError: USER_SITE = None try: import subprocess def _python_cmd(*args): args = (sys.executable,) + args return subprocess.call(args) == 0 except ImportError: # will be used for python 2.3 def _python_cmd(*args): args = (sys.executable,) + args # quoting arguments if windows if sys.platform == 'win32': def quote(arg): if ' ' in arg: return '"%s"' % arg return arg args = [quote(arg) for arg in args] return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 DEFAULT_VERSION = "0.6.15" DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" SETUPTOOLS_FAKED_VERSION = "0.6c11" SETUPTOOLS_PKG_INFO = """\ Metadata-Version: 1.0 Name: setuptools Version: %s Summary: xxxx Home-page: xxx Author: xxx Author-email: xxx License: xxx Description: xxx """ % SETUPTOOLS_FAKED_VERSION def _install(tarball): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # installing log.warn('Installing Distribute') if not _python_cmd('setup.py', 'install'): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') finally: os.chdir(old_wd) def _build_egg(egg, tarball, to_dir): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # building an egg log.warn('Building a Distribute egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) finally: os.chdir(old_wd) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, tarball, to_dir) sys.path.insert(0, egg) import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): if not no_fake: _fake_setuptools() raise ImportError except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("distribute>="+version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of distribute (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U distribute'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) finally: if not no_fake: _create_fake_setuptools_pkg_info(to_dir) def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15): """Download distribute from a specified location and return its filename `version` should be a valid distribute version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen tgz_name = "distribute-%s.tar.gz" % version url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: log.warn("Downloading %s", url) src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(saveto, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def _no_sandbox(function): def __no_sandbox(*args, **kw): try: from setuptools.sandbox import DirectorySandbox if not hasattr(DirectorySandbox, '_old'): def violation(*args): pass DirectorySandbox._old = DirectorySandbox._violation DirectorySandbox._violation = violation patched = True else: patched = False except ImportError: patched = False try: return function(*args, **kw) finally: if patched: DirectorySandbox._violation = DirectorySandbox._old del DirectorySandbox._old return __no_sandbox def _patch_file(path, content): """Will backup the file then patch it""" existing_content = open(path).read() if existing_content == content: # already patched log.warn('Already patched.') return False log.warn('Patching...') _rename_path(path) f = open(path, 'w') try: f.write(content) finally: f.close() return True _patch_file = _no_sandbox(_patch_file) def _same_content(path, content): return open(path).read() == content def _rename_path(path): new_name = path + '.OLD.%s' % time.time() log.warn('Renaming %s into %s', path, new_name) os.rename(path, new_name) return new_name def _remove_flat_installation(placeholder): if not os.path.isdir(placeholder): log.warn('Unkown installation at %s', placeholder) return False found = False for file in os.listdir(placeholder): if fnmatch.fnmatch(file, 'setuptools*.egg-info'): found = True break if not found: log.warn('Could not locate setuptools*.egg-info') return log.warn('Removing elements out of the way...') pkg_info = os.path.join(placeholder, file) if os.path.isdir(pkg_info): patched = _patch_egg_dir(pkg_info) else: patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) if not patched: log.warn('%s already patched.', pkg_info) return False # now let's move the files out of the way for element in ('setuptools', 'pkg_resources.py', 'site.py'): element = os.path.join(placeholder, element) if os.path.exists(element): _rename_path(element) else: log.warn('Could not find the %s element of the ' 'Setuptools distribution', element) return True _remove_flat_installation = _no_sandbox(_remove_flat_installation) def _after_install(dist): log.warn('After install bootstrap.') placeholder = dist.get_command_obj('install').install_purelib _create_fake_setuptools_pkg_info(placeholder) def _create_fake_setuptools_pkg_info(placeholder): if not placeholder or not os.path.exists(placeholder): log.warn('Could not find the install location') return pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) setuptools_file = 'setuptools-%s-py%s.egg-info' % \ (SETUPTOOLS_FAKED_VERSION, pyver) pkg_info = os.path.join(placeholder, setuptools_file) if os.path.exists(pkg_info): log.warn('%s already exists', pkg_info) return log.warn('Creating %s', pkg_info) f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() pth_file = os.path.join(placeholder, 'setuptools.pth') log.warn('Creating %s', pth_file) f = open(pth_file, 'w') try: f.write(os.path.join(os.curdir, setuptools_file)) finally: f.close() _create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info) def _patch_egg_dir(path): # let's check if it's already patched pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') if os.path.exists(pkg_info): if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): log.warn('%s already patched.', pkg_info) return False _rename_path(path) os.mkdir(path) os.mkdir(os.path.join(path, 'EGG-INFO')) pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() return True _patch_egg_dir = _no_sandbox(_patch_egg_dir) def _before_install(): log.warn('Before install bootstrap.') _fake_setuptools() def _under_prefix(location): if 'install' not in sys.argv: return True args = sys.argv[sys.argv.index('install')+1:] for index, arg in enumerate(args): for option in ('--root', '--prefix'): if arg.startswith('%s=' % option): top_dir = arg.split('root=')[-1] return location.startswith(top_dir) elif arg == option: if len(args) > index: top_dir = args[index+1] return location.startswith(top_dir) if arg == '--user' and USER_SITE is not None: return location.startswith(USER_SITE) return True def _fake_setuptools(): log.warn('Scanning installed packages') try: import pkg_resources except ImportError: # we're cool log.warn('Setuptools or Distribute does not seem to be installed.') return ws = pkg_resources.working_set try: setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools', replacement=False)) except TypeError: # old distribute API setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools')) if setuptools_dist is None: log.warn('No setuptools distribution found') return # detecting if it was already faked setuptools_location = setuptools_dist.location log.warn('Setuptools installation detected at %s', setuptools_location) # if --root or --preix was provided, and if # setuptools is not located in them, we don't patch it if not _under_prefix(setuptools_location): log.warn('Not patching, --root or --prefix is installing Distribute' ' in another location') return # let's see if its an egg if not setuptools_location.endswith('.egg'): log.warn('Non-egg installation') res = _remove_flat_installation(setuptools_location) if not res: return else: log.warn('Egg installation') pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') if (os.path.exists(pkg_info) and _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): log.warn('Already patched.') return log.warn('Patching...') # let's create a fake egg replacing setuptools one res = _patch_egg_dir(setuptools_location) if not res: return log.warn('Patched done.') _relaunch() def _relaunch(): log.warn('Relaunching...') # we have to relaunch the process # pip marker to avoid a relaunch bug if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']: sys.argv[0] = 'setup.py' args = [sys.executable] + sys.argv sys.exit(subprocess.call(args)) def _extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ import copy import operator from tarfile import ExtractError directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 448 # decimal for oct 0700 self.extract(tarinfo, path) # Reverse sort directories. if sys.version_info < (2, 4): def sorter(dir1, dir2): return cmp(dir1.name, dir2.name) directories.sort(sorter) directories.reverse() else: directories.sort(key=operator.attrgetter('name'), reverse=True) # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError: e = sys.exc_info()[1] if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball) if __name__ == '__main__': main(sys.argv[1:]) PyHamcrest-1.9.0/doc/000077500000000000000000000000001266666136400143655ustar00rootroot00000000000000PyHamcrest-1.9.0/doc/.gitignore000066400000000000000000000000101266666136400163440ustar00rootroot00000000000000_build/ PyHamcrest-1.9.0/doc/Makefile000066400000000000000000000110051266666136400160220ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest html: help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyHamcrest.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyHamcrest.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/PyHamcrest" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyHamcrest" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." PyHamcrest-1.9.0/doc/conf.py000066400000000000000000000167261266666136400157000ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # PyHamcrest documentation build configuration file, created by # sphinx-quickstart on Sat Dec 25 21:13:30 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os import six import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) from hamcrest import __version__ # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] autodoc_default_flags = ['members', 'show-inheritance'] intersphinx_mapping = {'python': ('http://docs.python.org/2.6', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = six.u('PyHamcrest') copyright = six.u('2011, hamcrest.org') # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. default_role = 'py:obj' # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] html_theme_path = [ sphinx_rtd_theme.get_html_theme_path() ] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PyHamcrestdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PyHamcrest.tex', six.u('PyHamcrest Documentation'), six.u('hamcrest.org'), 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # PyHamcrest customization: Don't skip BaseMatcher's _matches method def skip_member(app, what, name, obj, skip, options): if skip and str(obj).find('BaseMatcher._matches') >= 0: return False return skip def setup(app): app.connect('autodoc-skip-member', skip_member) # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pyhamcrest', six.u('PyHamcrest Documentation'), [six.u('hamcrest.org')], 1) ] PyHamcrest-1.9.0/doc/core.rst000066400000000000000000000011221266666136400160430ustar00rootroot00000000000000Core API ======== .. toctree:: helpers BaseDescription --------------- .. automodule:: hamcrest.core.base_description BaseMatcher ----------- .. automodule:: hamcrest.core.base_matcher :undoc-members: Description ----------- .. automodule:: hamcrest.core.description Matcher ------- .. automodule:: hamcrest.core.matcher SelfDescribing -------------- .. automodule:: hamcrest.core.selfdescribing SelfDescribingValue ------------------- .. automodule:: hamcrest.core.selfdescribingvalue StringDescription ----------------- .. automodule:: hamcrest.core.string_description PyHamcrest-1.9.0/doc/custom_matchers.rst000066400000000000000000000055611266666136400203260ustar00rootroot00000000000000Writing 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 :py:meth:`~hamcrest.core.base_matcher.BaseMatcher._matches` method - which calls the ``weekday`` method after confirming that the argument (which may not be a date) has such a method - and the :py:func:`~hamcrest.core.selfdescribing.SelfDescribing.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. PyHamcrest-1.9.0/doc/decorator_matchers.rst000066400000000000000000000005151266666136400207700ustar00rootroot00000000000000Decorator Matchers ------------------ Matchers that decorate other matchers for better expression. described_as ^^^^^^^^^^^^ .. automodule:: hamcrest.core.core.described_as :exclude-members: described_as .. autofunction:: described_as(description, matcher[, value1[, ...]]) is\_ ^^^^ .. automodule:: hamcrest.core.core.is_ PyHamcrest-1.9.0/doc/dictionary_matchers.rst000066400000000000000000000007611266666136400211560ustar00rootroot00000000000000Dictionary Matchers ------------------- Matchers of dictionaries. has_entries ^^^^^^^^^^^ .. automodule:: hamcrest.library.collection.isdict_containingentries :exclude-members: has_entries .. autofunction:: has_entries(matcher_dict) has_entry ^^^^^^^^^ .. automodule:: hamcrest.library.collection.isdict_containing has_key ^^^^^^^ .. automodule:: hamcrest.library.collection.isdict_containingkey has_value ^^^^^^^^^ .. automodule:: hamcrest.library.collection.isdict_containingvalue PyHamcrest-1.9.0/doc/helpers.rst000066400000000000000000000003061266666136400165600ustar00rootroot00000000000000Helpers ------- Utilities for writing Matchers hasmethod ^^^^^^^^^ .. automodule:: hamcrest.core.helpers.hasmethod wrap_matcher ^^^^^^^^^^^^ .. automodule:: hamcrest.core.helpers.wrap_matcher PyHamcrest-1.9.0/doc/index.rst000066400000000000000000000004001266666136400162200ustar00rootroot00000000000000PyHamcrest documentation ======================== Contents: .. toctree:: :maxdepth: 1 tutorial custom_matchers library integration core Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` PyHamcrest-1.9.0/doc/integration.rst000066400000000000000000000005231266666136400174420ustar00rootroot00000000000000Integration with PyUnit and Other Libraries =========================================== assert_that ----------- .. automodule:: hamcrest.core.assert_that :exclude-members: assert_that .. autofunction:: assert_that(actual, matcher[, reason]) match_equality -------------- .. automodule:: hamcrest.library.integration.match_equality PyHamcrest-1.9.0/doc/library.rst000066400000000000000000000003501266666136400165610ustar00rootroot00000000000000Matcher Library =============== Library of Matcher implementations. .. toctree:: object_matchers number_matchers text_matchers logical_matchers sequence_matchers dictionary_matchers decorator_matchers PyHamcrest-1.9.0/doc/logical_matchers.rst000066400000000000000000000010441266666136400204160ustar00rootroot00000000000000Logical Matchers ---------------- Boolean logic using other matchers. all_of ^^^^^^ .. automodule:: hamcrest.core.core.allof :exclude-members: all_of .. autofunction:: all_of(matcher1[, matcher2[, ...]]) any_of ^^^^^^ .. automodule:: hamcrest.core.core.anyof :exclude-members: any_of .. autofunction:: any_of(matcher1[, matcher2[, ...]]) anything ^^^^^^^^ .. automodule:: hamcrest.core.core.isanything :exclude-members: anything .. autofunction:: anything([description]) is_not ^^^^^^ .. automodule:: hamcrest.core.core.isnot PyHamcrest-1.9.0/doc/number_matchers.rst000066400000000000000000000005431266666136400202770ustar00rootroot00000000000000Number Matchers --------------- Matchers that perform numeric comparisons. close_to ^^^^^^^^ .. automodule:: hamcrest.library.number.iscloseto greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.number.ordering_comparison PyHamcrest-1.9.0/doc/object_matchers.rst000066400000000000000000000012521266666136400202530ustar00rootroot00000000000000Object Matchers --------------- Matchers that inspect objects. equal_to ^^^^^^^^ .. automodule:: hamcrest.core.core.isequal has_length ^^^^^^^^^^ .. automodule:: hamcrest.library.object.haslength has_string ^^^^^^^^^^ .. automodule:: hamcrest.library.object.hasstring has_properties/has_property ^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.object.hasproperty instance_of ^^^^^^^^^^^ .. automodule:: hamcrest.core.core.isinstanceof none, not_none ^^^^^^^^^^^^^^ .. automodule:: hamcrest.core.core.isnone same_instance ^^^^^^^^^^^^^ .. automodule:: hamcrest.core.core.issame calling, raises ^^^^^^^^^^^^^^^ .. automodule:: hamcrest.core.core.raises PyHamcrest-1.9.0/doc/sequence_matchers.rst000066400000000000000000000020061266666136400206130ustar00rootroot00000000000000Sequence Matchers ----------------- Matchers of sequences. contains ^^^^^^^^ .. automodule:: hamcrest.library.collection.issequence_containinginorder :exclude-members: contains .. autofunction:: contains(match1, [match2[, ...]]) contains_inanyorder ^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.collection.issequence_containinginanyorder :exclude-members: contains_inanyorder .. autofunction:: contains_inanyorder(match1, [match2[, ...]]) has_item, has_items ^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.collection.issequence_containing :exclude-members: has_items .. autofunction:: has_items(match1, [match2[, ...]]) is_in ^^^^^ .. automodule:: hamcrest.library.collection.isin only_contains ^^^^^^^^^^^^^ .. automodule:: hamcrest.library.collection.issequence_onlycontaining :exclude-members: only_contains .. autofunction:: only_contains(match1, [match2[, ...]]) empty ^^^^^ .. automodule:: hamcrest.library.collection.is_empty :exclude-members: empty .. autofunction:: empty() PyHamcrest-1.9.0/doc/text_matchers.rst000066400000000000000000000015351266666136400177750ustar00rootroot00000000000000Text Matchers ------------- Matchers that perform text comparisons. contains_string ^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.text.stringcontains ends_with ^^^^^^^^^ .. automodule:: hamcrest.library.text.stringendswith equal_to_ignoring_case ^^^^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.text.isequal_ignoring_case equal_to_ignoring_whitespace ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.text.isequal_ignoring_whitespace matches_regexp ^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.text.stringmatches starts_with ^^^^^^^^^^^ .. automodule:: hamcrest.library.text.stringstartswith string_contains_in_order ^^^^^^^^^^^^^^^^^^^^^^^^ .. automodule:: hamcrest.library.text.stringcontainsinorder :exclude-members: string_contains_in_order .. autofunction:: string_contains_in_order(string1[, string2[, ...]]) PyHamcrest-1.9.0/doc/tutorial.rst000066400000000000000000000222201266666136400167600ustar00rootroot00000000000000PyHamcrest Tutorial =================== 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. My first PyHamcrest test ------------------------ We'll start by writing a very simple PyUnit test, but instead of using PyUnit's :py:meth:`~unittest.TestCase.assertEqual` method, we'll use PyHamcrest's :py:func:`~hamcrest.core.matcher_assert.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 :py:func:`~hamcrest.core.matcher_assert.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, :py:func:`~hamcrest.core.matcher_assert.assert_that` can also be used to verify a boolean condition:: assert_that(theBiscuit.isCooked(), 'cooked') This is equivalent to the :py:meth:`~unittest.TestCase.assert_` method of :py:class:`unittest.TestCase`, but because it's a standalone function, it offers greater flexibility in test writing. Asserting Exceptions -------------------- There's a utility function and matcher available to help you test that your code has the expected behavior in situations where it should raise an exception. The :py:func:`~hamcrest.core.core.raises.calling` function wraps a callable, and then allows you to set arguments to be used in a call to the wrapped callable. This, together with the :py:func:`~hamcrest.core.core.raises.raises` matcher lets you assert that calling a method with certain arguments causes an exception to be thrown. It is also possible to provide a regular expression pattern to the :py:func:`~hamcrest.core.core.raises.raises` matcher allowing you assure that the right issue was found:: 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)) Predefined matchers ------------------- PyHamcrest comes with a library of useful matchers: * Object * :py:func:`~hamcrest.core.core.isequal.equal_to` - match equal object * :py:func:`~hamcrest.library.object.haslength.has_length` - match ``len(item)`` * :py:func:`~hamcrest.library.object.hasproperty.has_property` - match value of property with given name * :py:func:`~hamcrest.library.object.hasproperty.has_properties` - match an object that has all of the given properties. * :py:func:`~hamcrest.library.object.hasstring.has_string` - match ``str(item)`` * :py:func:`~hamcrest.core.core.isinstanceof.instance_of` - match object type * :py:func:`~hamcrest.core.core.isnone.none`, :py:func:`~hamcrest.core.core.isnone.not_none` - match ``None``, or not ``None`` * :py:func:`~hamcrest.core.core.issame.same_instance` - match same object * :py:func:`~hamcrest.core.core.raises.calling`, :py:func:`~hamcrest.core.core.raises.raises` - wrap a method call and assert that it raises an exception * Number * :py:func:`~hamcrest.library.number.iscloseto.close_to` - match number close to a given value * :py:func:`~hamcrest.library.number.ordering_comparison.greater_than`, :py:func:`~hamcrest.library.number.ordering_comparison.greater_than_or_equal_to`, :py:func:`~hamcrest.library.number.ordering_comparison.less_than`, :py:func:`~hamcrest.library.number.ordering_comparison.less_than_or_equal_to` - match numeric ordering * Text * :py:func:`~hamcrest.library.text.stringcontains.contains_string` - match part of a string * :py:func:`~hamcrest.library.text.stringendswith.ends_with` - match the end of a string * :py:func:`~hamcrest.library.text.isequal_ignoring_case.equal_to_ignoring_case` - match the complete string but ignore case * :py:func:`~hamcrest.library.text.isequal_ignoring_whitespace.equal_to_ignoring_whitespace` - match the complete string but ignore extra whitespace * :py:func:`~hamcrest.library.text.stringstartswith.starts_with` - match the beginning of a string * :py:func:`~hamcrest.library.text.stringcontainsinorder.string_contains_in_order` - match parts of a string, in relative order * Logical * :py:func:`~hamcrest.core.core.allof.all_of` - ``and`` together all matchers * :py:func:`~hamcrest.core.core.anyof.any_of` - ``or`` together all matchers * :py:func:`~hamcrest.core.core.isanything.anything` - match anything, useful in composite matchers when you don't care about a particular value * :py:func:`~hamcrest.core.core.isnot.is_not` - negate the matcher * Sequence * :py:func:`~hamcrest.library.collection.issequence_containinginorder.contains` - exactly match the entire sequence * :py:func:`~hamcrest.library.collection.issequence_containinginanyorder.contains_inanyorder` - match the entire sequence, but in any order * :py:func:`~hamcrest.library.collection.issequence_containing.has_item` - match if given item appears in the sequence * :py:func:`~hamcrest.library.collection.issequence_containing.has_items` - match if all given items appear in the list, in any order * :py:func:`~hamcrest.library.collection.isin.is_in` - match if item appears in the given sequence * :py:func:`~hamcrest.library.collection.issequence_onlycontaining.only_contains` - match if sequence's items appear in given list * :py:func:`~hamcrest.library.collection.is_empty.empty` - match if the sequence is empty * Dictionary * :py:func:`~hamcrest.library.collection.isdict_containingentries.has_entries` - match dictionary with list of key-value pairs * :py:func:`~hamcrest.library.collection.isdict_containing.has_entry` - match dictionary containing a key-value pair * :py:func:`~hamcrest.library.collection.isdict_containingkey.has_key` - match dictionary with a key * :py:func:`~hamcrest.library.collection.isdict_containingvalue.has_value` - match dictionary with a value * Decorator * :py:func:`~hamcrest.core.core.described_as.described_as` - give the matcher a custom failure description * :py:func:`~hamcrest.core.core.is_.is_` - decorator to improve readability - see :ref:`sugar`, below 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, ``only_contains(less_than(5))`` will match any sequence where every item is less than 5. .. _sugar: Syntactic sugar --------------- PyHamcrest strives to make your tests as readable as possible. For example, the :py:func:`~hamcrest.core.core.is_.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 :py:func:`~hamcrest.core.core.isequal.equal_to`. But if the argument is a type, it is wrapped with :py:func:`~hamcrest.core.core.isinstanceof.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 :py:func:`~hamcrest.core.core.issame.same_instance`.) PyHamcrest-1.9.0/docker/000077500000000000000000000000001266666136400150675ustar00rootroot00000000000000PyHamcrest-1.9.0/docker/Dockerfile000066400000000000000000000030421266666136400170600ustar00rootroot00000000000000FROM ubuntu:14.04 MAINTAINER Chris Rose # ensure the base image has what we need RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get -yqq install \ build-essential python-pip \ software-properties-common openjdk-7-jdk && \ add-apt-repository ppa:fkrull/deadsnakes && \ apt-get update # install legacy python versions RUN DEBIAN_FRONTEND=noninteractive apt-get -yqq install \ python2.5 python2.6 python2.7 python3.1 python3.2 python3.3 python3.4 # add Jython installer # ADD jython-installer-2.7-b4.jar /tmp/ ADD http://search.maven.org/remotecontent?filepath=org/python/jython-installer/2.7-b4/jython-installer-2.7-b4.jar /tmp/jython-installer-2.7-b4.jar # install pypy versions # ADD pypy-2.5.0-linux64.tar.bz2 /opt/ # ADD pypy3-2.4.0-linux64.tar.bz2 /opt/ RUN mkdir -p /opt ADD https://bitbucket.org/pypy/pypy/downloads/pypy3-2.4.0-linux64.tar.bz2 /tmp/ RUN cd /opt && tar -xf /tmp/pypy3-2.4.0-linux64.tar.bz2 ADD https://bitbucket.org/pypy/pypy/downloads/pypy-2.5.0-linux64.tar.bz2 /tmp/ RUN cd /opt && tar -xf /tmp/pypy-2.5.0-linux64.tar.bz2 # install Jython version RUN java -jar /tmp/jython-installer-2.7-b4.jar -d /opt/jython-2.7-b4 -s -t all ENV PATH /opt/jython-2.7-b4/bin:$PATH # bootstrap jython JAR cache RUN jython # make PyPy available ENV PATH /opt/pypy-2.5.0-linux64/bin:/opt/pypy3-2.4.0-linux64/bin:$PATH ENV PYTHON_BUILD_DOCKER=true # install tox RUN pip install tox ADD clean-launch.sh /tools/clean-launch.sh VOLUME /src WORKDIR /src ENTRYPOINT ["/tools/clean-launch.sh"] CMD ["tox"] PyHamcrest-1.9.0/docker/README.md000066400000000000000000000012761266666136400163540ustar00rootroot00000000000000# Test hamcrest with Docker ## Simple testing steps (this assumes that you have [Docker](https://docker.com) installed) 1. cd to the directory containing PyHamcrest's `tox.ini` file. 2. run `docker run --rm -v $(pwd):/src chrisr/pybuilder:latest` That's it! This will test PyHamcrest with all supported versions of Python ## Tweaking the build image 1. in this directory, modify the `Dockerfile` to have the setup you want 2. `docker build --tag $USER/pybuilder:latest .` 3. run your build 4. submit a pull request to the `hamcrest/PyHamcrest` repo with your changes to the Dockerfile We'll merge and publish the new tag to `chrisr/pybuilder:latest`, making the new instructions up to date. PyHamcrest-1.9.0/docker/clean-launch.sh000077500000000000000000000001211266666136400177520ustar00rootroot00000000000000#!/bin/bash find /src \( -name __pycache__ -o -name '*.pyc' \) -delete exec "$@" PyHamcrest-1.9.0/examples/000077500000000000000000000000001266666136400154365ustar00rootroot00000000000000PyHamcrest-1.9.0/examples/CustomDateMatcher.py000066400000000000000000000031221266666136400213620ustar00rootroot00000000000000import sys sys.path.append('..') from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest import * import unittest import datetime class IsGivenDayOfWeek(BaseMatcher): """Matches dates that fall on a given day of the week.""" def __init__(self, day): self.day = day # Monday is 0, Sunday is 6 def _matches(self, item): """Test whether item matches.""" if not hasmethod(item, 'weekday'): return False return item.weekday() == self.day def describe_to(self, description): """Describe the matcher.""" 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(): """Factory function to generate Saturday matcher.""" return IsGivenDayOfWeek(5) class SampleTest(unittest.TestCase): def testDateIsOnASaturday(self): """Example of successful match.""" d = datetime.date(2008, 04, 26) assert_that(d, is_(on_a_saturday())) def testFailsWithMismatchedDate(self): """Example of what happens with date that doesn't match.""" d = datetime.date(2008, 04, 06) assert_that(d, is_(on_a_saturday())) def testFailsWithNonDate(self): """Example of what happens with object that isn't a date.""" d = 'oops' assert_that(d, is_(on_a_saturday())) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/examples/ExampleWithAssertThat.py000066400000000000000000000010501266666136400222360ustar00rootroot00000000000000import sys sys.path.append('..') from hamcrest import * import unittest class ExampleWithAssertThat(unittest.TestCase): def testUsingAssertThat(self): assert_that('xx', is_('xx')) assert_that('yy', is_not('xx')) assert_that('i like cheese', contains_string('cheese')) def testCanAlsoSupplyDescriptiveReason(self): assert_that('xx', is_('xx'), 'description') def testCanAlsoAssertPlainBooleans(self): assert_that(True, 'This had better not fail') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/pytest.ini000066400000000000000000000001151266666136400156460ustar00rootroot00000000000000[pytest] addopts = --cov hamcrest --cov-report term-missing --no-cov-on-fail PyHamcrest-1.9.0/release.sh000077500000000000000000000020171266666136400155770ustar00rootroot00000000000000#!/usr/bin/env bash HERE=$(unset CDPATH; cd `dirname $0`; pwd) cd $HERE function do_release() { local rc local ver=$1; shift local python=${1:-python}; shift rm -rf $HERE/build $HERE/.tox/$ver/bin/$python $HERE/setup.py build bdist_egg upload rc=$? return $rc } function do_test() { local rc local ver=$1; shift local python=${1:-python}; shift rm -rf $HERE/build tox -e $ver rc=$? return $rc } function do_all_vers() { for python_version in py26 py27 py32 py33 py34; do $1 $python_version || failed="$failed $python_version" done $1 pypy pypy || failed="$failed pypy" # $1 jython jython || failed="$failed jython" rc=0 for f in $failed; do rc=1 echo "$1 failed for $f" done if [ $rc -ne 0 ]; then echo "Skipping $1 due to failures" return $rc fi } do_all_vers do_test || exit 1 do_all_vers do_release || exit 1 echo "All releases uploaded; uploading source release as well" tox -e wheel exit $rc PyHamcrest-1.9.0/requirements.txt000066400000000000000000000000111266666136400170740ustar00rootroot00000000000000six>=1.4 PyHamcrest-1.9.0/setup.cfg000066400000000000000000000001231266666136400154350ustar00rootroot00000000000000[egg_info] ;tag_build = .dev ;tag_svn_revision = true [bdist_wheel] universal = 1 PyHamcrest-1.9.0/setup.py000077500000000000000000000060411266666136400153360ustar00rootroot00000000000000import sys import os import re # need to kill off link if we're in docker builds if os.environ.get('PYTHON_BUILD_DOCKER', None) == 'true': del os.link try: from setuptools import setup, find_packages except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def local(fname): return os.path.join(os.path.dirname(__file__), fname) def read(fname): return open(local(fname)).read() # On Python 3, we can't "from hamcrest import __version__" (get ImportError), # so we extract the variable assignment and execute it ourselves. fh = open(local('src/hamcrest/__init__.py')) try: for line in fh: if re.match('__version__.*', line): exec(line) finally: if fh: fh.close() class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ["tests"] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) test_dependencies = ['hypothesis>=1.11', 'pytest>=2.8', 'mock', 'pytest-cov'] try: from unittest import skipIf except ImportError: test_dependencies.append('unittest2') extra_attributes = {} # if sys.version_info >= (3,): # extra_attributes['use_2to3'] = True params = dict( name='PyHamcrest', version=__version__, #flake8:noqa author='Chris Rose', author_email='offline@offby1.net', description='Hamcrest framework for matcher objects', license='New BSD', platforms=['All'], keywords='hamcrest matchers pyunit unit test testing unittest unittesting', url='https://github.com/hamcrest/PyHamcrest', download_url='http://pypi.python.org/packages/source/P/PyHamcrest/PyHamcrest-%s.tar.gz' % __version__, packages=find_packages('src'), package_dir = {'': 'src'}, provides=['hamcrest'], long_description=read('README.rst'), install_requires=['setuptools', 'six'], tests_require=test_dependencies, cmdclass={'test': PyTest}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: Jython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', ], **extra_attributes ) all_params = dict(params.items(), **extra_attributes) setup(**all_params) PyHamcrest-1.9.0/src/000077500000000000000000000000001266666136400144075ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/000077500000000000000000000000001266666136400162155ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/__init__.py000066400000000000000000000003461266666136400203310ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.core import * from hamcrest.library import * __version__ = "1.9.0" __author__ = "Chris Rose" __copyright__ = "Copyright 2015 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/core/000077500000000000000000000000001266666136400171455ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/core/__init__.py000066400000000000000000000003461266666136400212610ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.core.assert_that import assert_that from hamcrest.core.core import * __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/core/assert_that.py000066400000000000000000000045741266666136400220520ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.core.matcher import Matcher from hamcrest.core.string_description import StringDescription __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" # unittest integration; hide these frames from tracebacks __unittest = True # py.test integration; hide these frames from tracebacks __tracebackhide__ = True def assert_that(arg1, arg2=None, arg3=''): """Asserts that actual value satisfies matcher. (Can also assert plain boolean condition.) :param actual: The object to evaluate as the actual value. :param matcher: The matcher to satisfy as the expected condition. :param reason: Optional explanation to include in failure description. ``assert_that`` passes the actual value to the matcher for evaluation. If the matcher is not satisfied, an exception is thrown describing the mismatch. ``assert_that`` is designed to integrate well with PyUnit and other unit testing frameworks. The exception raised for an unmet assertion is an :py:exc:`AssertionError`, which PyUnit reports as a test failure. With a different set of parameters, ``assert_that`` can also verify a boolean condition: .. function:: assert_that(assertion[, reason]) :param assertion: Boolean condition to verify. :param reason: Optional explanation to include in failure description. This is equivalent to the :py:meth:`~unittest.TestCase.assertTrue` method of :py:class:`unittest.TestCase`, but offers greater flexibility in test writing by being a standalone function. """ if isinstance(arg2, Matcher): _assert_match(actual=arg1, matcher=arg2, reason=arg3) else: _assert_bool(assertion=arg1, reason=arg2) def _assert_match(actual, matcher, reason): if not matcher.matches(actual): description = StringDescription() description.append_text(reason) \ .append_text('\nExpected: ') \ .append_description_of(matcher) \ .append_text('\n but: ') matcher.describe_mismatch(actual, description) description.append_text('\n') raise AssertionError(description) def _assert_bool(assertion, reason=None): if not assertion: if not reason: reason = 'Assertion failed' raise AssertionError(reason) PyHamcrest-1.9.0/src/hamcrest/core/base_description.py000066400000000000000000000054311266666136400230370ustar00rootroot00000000000000from __future__ import absolute_import __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import warnings import six from hamcrest.core.description import Description from hamcrest.core.selfdescribingvalue import SelfDescribingValue from hamcrest.core.helpers.hasmethod import hasmethod class BaseDescription(Description): """Base class for all :py:class:`~hamcrest.core.description.Description` implementations. """ def append_text(self, text): self.append(text) return self def append_description_of(self, value): if hasmethod(value, 'describe_to'): value.describe_to(self) elif six.PY3 and isinstance(value, six.text_type): self.append(repr(value)) elif six.PY2 and isinstance(value, six.binary_type): self.append_string_in_python_syntax(value) elif isinstance(value, six.text_type): self.append_string_in_python_syntax(value) else: description = str(value) if description[:1] == '<' and description[-1:] == '>': self.append(description) else: self.append('<') self.append(description) self.append('>') return self def append_value(self, value): warnings.warn('Call append_description_of instead of append_value', DeprecationWarning) if isinstance(value, str): self.append_string_in_python_syntax(value) else: self.append('<') self.append(str(value)) self.append('>') return self def append_value_list(self, start, separator, end, list): warnings.warn('Call append_list instead of append_value_list', DeprecationWarning) return self.append_list(start, separator, end, map(SelfDescribingValue, list)) def append_list(self, start, separator, end, list): separate = False self.append(start) for item in list: if separate: self.append(separator) self.append_description_of(item) separate = True self.append(end) return self def append(self, string): """Append the string to the description.""" raise NotImplementedError('append') def append_string_in_python_syntax(self, string): self.append("'") for ch in string: self.append(character_in_python_syntax(ch)) self.append("'") def character_in_python_syntax(ch): if ch == "'": return "\'" elif ch == '\n': return '\\n' elif ch == '\r': return '\\r' elif ch == '\t': return '\\t' else: return ch PyHamcrest-1.9.0/src/hamcrest/core/base_matcher.py000066400000000000000000000022511266666136400221340ustar00rootroot00000000000000from __future__ import absolute_import __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.matcher import Matcher from hamcrest.core.string_description import tostring class BaseMatcher(Matcher): """Base class for all :py:class:`~hamcrest.core.matcher.Matcher` implementations. Most implementations can just implement :py:obj:`_matches`, leaving the handling of any mismatch description to the ``matches`` method. But if it makes more sense to generate the mismatch description during the matching, override :py:meth:`~hamcrest.core.matcher.Matcher.matches` instead. """ def __str__(self): return tostring(self) def _matches(self, item): raise NotImplementedError('_matches') def matches(self, item, mismatch_description=None): match_result = self._matches(item) if not match_result and mismatch_description: self.describe_mismatch(item, mismatch_description) return match_result def describe_mismatch(self, item, mismatch_description): mismatch_description.append_text('was ').append_description_of(item) PyHamcrest-1.9.0/src/hamcrest/core/compat.py000066400000000000000000000012021266666136400207750ustar00rootroot00000000000000__author__ = "Per Fagrell" __copyright__ = "Copyright 2013 hamcrest.org" __license__ = "BSD, see License.txt" __all__ = ['is_callable'] import sys # callable was not part of py3k until 3.2, so we create this # generic is_callable to use callable if possible, otherwise # we use generic homebrew. if sys.version_info[0] == 3 and sys.version_info[1] < 2: def is_callable(function): """Return whether the object is callable (i.e., some kind of function).""" if function is None: return False return any("__call__" in klass.__dict__ for klass in type(function).__mro__) else: is_callable = callable PyHamcrest-1.9.0/src/hamcrest/core/core/000077500000000000000000000000001266666136400200755ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/core/core/__init__.py000066400000000000000000000014021266666136400222030ustar00rootroot00000000000000from __future__ import absolute_import """Fundamental matchers of objects and values, and composite matchers.""" from hamcrest.core.core.allof import all_of from hamcrest.core.core.anyof import any_of from hamcrest.core.core.described_as import described_as from hamcrest.core.core.is_ import is_ from hamcrest.core.core.isanything import anything from hamcrest.core.core.isequal import equal_to from hamcrest.core.core.isinstanceof import instance_of from hamcrest.core.core.isnone import none, not_none from hamcrest.core.core.isnot import is_not, not_ from hamcrest.core.core.issame import same_instance from hamcrest.core.core.raises import calling, raises __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/core/core/allof.py000066400000000000000000000027171266666136400215530ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class AllOf(BaseMatcher): def __init__(self, *matchers): self.matchers = matchers def matches(self, item, mismatch_description=None): for matcher in self.matchers: if not matcher.matches(item): if mismatch_description: mismatch_description.append_description_of(matcher) \ .append_text(' ') matcher.describe_mismatch(item, mismatch_description) return False return True def describe_mismatch(self, item, mismatch_description): self.matches(item, mismatch_description) def describe_to(self, description): description.append_list('(', ' and ', ')', self.matchers) def all_of(*items): """Matches if all of the given matchers evaluate to ``True``. :param matcher1,...: A comma-separated list of matchers. The matchers are evaluated from left to right using short-circuit evaluation, so evaluation stops as soon as a matcher returns ``False``. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ return AllOf(*[wrap_matcher(item) for item in items]) PyHamcrest-1.9.0/src/hamcrest/core/core/anyof.py000066400000000000000000000021111266666136400215560ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class AnyOf(BaseMatcher): def __init__(self, *matchers): self.matchers = matchers def _matches(self, item): for matcher in self.matchers: if matcher.matches(item): return True return False def describe_to(self, description): description.append_list('(', ' or ', ')', self.matchers) def any_of(*items): """Matches if any of the given matchers evaluate to ``True``. :param matcher1,...: A comma-separated list of matchers. The matchers are evaluated from left to right using short-circuit evaluation, so evaluation stops as soon as a matcher returns ``True``. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ return AnyOf(*[wrap_matcher(item) for item in items]) PyHamcrest-1.9.0/src/hamcrest/core/core/described_as.py000066400000000000000000000031271266666136400230610ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher import re __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" ARG_PATTERN = re.compile('%([0-9]+)') class DescribedAs(BaseMatcher): def __init__(self, description_template, matcher, *values): self.template = description_template self.matcher = matcher self.values = values def matches(self, item, mismatch_description=None): return self.matcher.matches(item, mismatch_description) def describe_mismatch(self, item, mismatch_description): self.matcher.describe_mismatch(item, mismatch_description) def describe_to(self, description): text_start = 0 for match in re.finditer(ARG_PATTERN, self.template): description.append_text(self.template[text_start:match.start()]) arg_index = int(match.group()[1:]) description.append_description_of(self.values[arg_index]) text_start = match.end() if text_start < len(self.template): description.append_text(self.template[text_start:]) def described_as(description, matcher, *values): """Adds custom failure description to a given matcher. :param description: Overrides the matcher's description. :param matcher: The matcher to satisfy. :param value1,...: Optional comma-separated list of substitution values. The description may contain substitution placeholders %0, %1, etc. These will be replaced by any values that follow the matcher. """ return DescribedAs(description, matcher, *values) PyHamcrest-1.9.0/src/hamcrest/core/core/is_.py000066400000000000000000000047631266666136400212330ustar00rootroot00000000000000from __future__ import absolute_import __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher, is_matchable_type from .isinstanceof import instance_of class Is(BaseMatcher): def __init__(self, matcher): self.matcher = matcher def matches(self, item, mismatch_description=None): return self.matcher.matches(item, mismatch_description) def describe_mismatch(self, item, mismatch_description): return self.matcher.describe_mismatch(item, mismatch_description) def describe_to(self, description): description.append_description_of(self.matcher) def wrap_value_or_type(x): if is_matchable_type(x): return instance_of(x) else: return wrap_matcher(x) def is_(x): """Decorates another matcher, or provides shortcuts to the frequently used ``is(equal_to(x))`` and ``is(instance_of(x))``. :param x: The matcher to satisfy, or a type for :py:func:`~hamcrest.core.core.isinstanceof.instance_of` matching, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher compares the evaluated object to the given matcher. .. note:: PyHamcrest's ``is_`` matcher is unrelated to Python's ``is`` operator. The matcher for object identity is :py:func:`~hamcrest.core.core.issame.same_instance`. If the ``x`` argument is a matcher, its behavior is retained, but the test may be more expressive. For example:: assert_that(value, less_than(5)) assert_that(value, is_(less_than(5))) If the ``x`` argument is a type, it is wrapped in an :py:func:`~hamcrest.core.core.isinstanceof.instance_of` matcher. This makes the following statements equivalent:: assert_that(cheese, instance_of(Cheddar)) assert_that(cheese, is_(instance_of(Cheddar))) assert_that(cheese, is_(Cheddar)) Otherwise, if the ``x`` argument is not a matcher, it is wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher. This makes the following statements equivalent:: assert_that(cheese, equal_to(smelly)) assert_that(cheese, is_(equal_to(smelly))) assert_that(cheese, is_(smelly)) Choose the style that makes your expression most readable. This will vary depending on context. """ return Is(wrap_value_or_type(x)) PyHamcrest-1.9.0/src/hamcrest/core/core/isanything.py000066400000000000000000000014361266666136400226300ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsAnything(BaseMatcher): def __init__(self, description): self.description = description if not description: self.description = 'ANYTHING' def _matches(self, item): return True def describe_to(self, description): description.append_text(self.description) def anything(description=None): """Matches anything. :param description: Optional string used to describe this matcher. This matcher always evaluates to ``True``. Specify this in composite matchers when the value of a particular element is unimportant. """ return IsAnything(description) PyHamcrest-1.9.0/src/hamcrest/core/core/isequal.py000066400000000000000000000015751266666136400221220ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.matcher import Matcher class IsEqual(BaseMatcher): def __init__(self, equals): self.object = equals def _matches(self, item): return item == self.object def describe_to(self, description): nested_matcher = isinstance(self.object, Matcher) if nested_matcher: description.append_text('<') description.append_description_of(self.object) if nested_matcher: description.append_text('>') def equal_to(obj): """Matches if object is equal to a given object. :param obj: The object to compare against as the expected value. This matcher compares the evaluated object to ``obj`` for equality.""" return IsEqual(obj) PyHamcrest-1.9.0/src/hamcrest/core/core/isinstanceof.py000066400000000000000000000025101266666136400231320ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import is_matchable_type __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types class IsInstanceOf(BaseMatcher): def __init__(self, expected_type): if not is_matchable_type(expected_type): raise TypeError('IsInstanceOf requires type or a tuple of classes and types') self.expected_type = expected_type def _matches(self, item): return isinstance(item, self.expected_type) def describe_to(self, description): try: type_description = self.expected_type.__name__ except AttributeError: type_description = "one of %s" % ",".join(str(e) for e in self.expected_type) description.append_text('an instance of ') \ .append_text(type_description) def instance_of(atype): """Matches if object is an instance of, or inherits from, a given type. :param atype: The type to compare against as the expected type or a tuple of types. This matcher checks whether the evaluated object is an instance of ``atype`` or an instance of any class that inherits from ``atype``. Example:: instance_of(str) """ return IsInstanceOf(atype) PyHamcrest-1.9.0/src/hamcrest/core/core/isnone.py000066400000000000000000000010551266666136400217430ustar00rootroot00000000000000from __future__ import absolute_import __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher from .isnot import is_not class IsNone(BaseMatcher): def _matches(self, item): return item is None def describe_to(self, description): description.append_text('None') def none(): """Matches if object is ``None``.""" return IsNone() def not_none(): """Matches if object is not ``None``.""" return is_not(none()) PyHamcrest-1.9.0/src/hamcrest/core/core/isnot.py000066400000000000000000000027751266666136400216160ustar00rootroot00000000000000from __future__ import absolute_import __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher, Matcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher, is_matchable_type from .isequal import equal_to from .isinstanceof import instance_of class IsNot(BaseMatcher): def __init__(self, matcher): self.matcher = matcher def _matches(self, item): return not self.matcher.matches(item) def describe_to(self, description): description.append_text('not ').append_description_of(self.matcher) def wrap_value_or_type(x): if is_matchable_type(x): return instance_of(x) else: return wrap_matcher(x) def is_not(match): """Inverts the given matcher to its logical negation. :param match: The matcher to negate. This matcher compares the evaluated object to the negation of the given matcher. If the ``match`` argument is not a matcher, it is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality, and thus matches for inequality. Examples:: assert_that(cheese, is_not(equal_to(smelly))) assert_that(cheese, is_not(smelly)) """ return IsNot(wrap_value_or_type(match)) def not_(match): """Alias of :py:func:`is_not` for better readability of negations. Examples:: assert_that(alist, not_(has_item(item))) """ return is_not(match) PyHamcrest-1.9.0/src/hamcrest/core/core/issame.py000066400000000000000000000023551266666136400217350ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher class IsSame(BaseMatcher): def __init__(self, object): self.object = object def _matches(self, item): return item is self.object def describe_to(self, description): description.append_text('same instance as ') \ .append_text(hex(id(self.object))) \ .append_text(' ') \ .append_description_of(self.object) def describe_mismatch(self, item, mismatch_description): mismatch_description.append_text('was ') if item is not None: mismatch_description.append_text(hex(id(item))) \ .append_text(' ') mismatch_description.append_description_of(item) def same_instance(obj): """Matches if evaluated object is the same instance as a given object. :param obj: The object to compare against as the expected value. This matcher invokes the ``is`` identity operator to determine if the evaluated object is the the same object as ``obj``. """ return IsSame(obj) PyHamcrest-1.9.0/src/hamcrest/core/core/raises.py000066400000000000000000000070321266666136400217370ustar00rootroot00000000000000from weakref import ref import re import sys from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.compat import is_callable __author__ = "Per Fagrell" __copyright__ = "Copyright 2013 hamcrest.org" __license__ = "BSD, see License.txt" class Raises(BaseMatcher): def __init__(self, expected, pattern=None): self.pattern = pattern self.expected = expected self.actual = None self.function = None def _matches(self, function): if not is_callable(function): return False self.function = ref(function) return self._call_function(function) def _call_function(self, function): self.actual = None try: function() except Exception: self.actual = sys.exc_info()[1] if isinstance(self.actual, self.expected): if self.pattern is not None: return re.search(self.pattern, str(self.actual)) is not None return True return False def describe_to(self, description): description.append_text('Expected a callable raising %s' % self.expected) def describe_mismatch(self, item, description): if not is_callable(item): description.append_text('%s is not callable' % item) return function = None if self.function is None else self.function() if function is None or function is not item: self.function = ref(item) if not self._call_function(item): return if self.actual is None: description.append_text('No exception raised.') elif isinstance(self.actual, self.expected) and self.pattern is not None: description.append_text('Correct assertion type raised, but the expected pattern ("%s") not found.' % self.pattern) description.append_text('\n message was: "%s"' % str(self.actual)) else: description.append_text('%s was raised instead' % type(self.actual)) def raises(exception, pattern=None): """Matches if the called function raised the expected exception. :param exception: The class of the expected exception :param pattern: Optional regular expression to match exception message. Expects the actual to be wrapped by using :py:func:`~hamcrest.core.core.raises.calling`, or a callable taking no arguments. Optional argument pattern should be a string containing a regular expression. If provided, the string representation of the actual exception - e.g. `str(actual)` - must match pattern. Examples:: assert_that(calling(int).with_args('q'), raises(TypeError)) assert_that(calling(parse, broken_input), raises(ValueError)) """ return Raises(exception, pattern) class DeferredCallable(object): def __init__(self, func): self.func = func self.args = tuple() self.kwargs = {} def __call__(self): return self.func(*self.args, **self.kwargs) def with_args(self, *args, **kwargs): self.args = args self.kwargs = kwargs return self def calling(func): """Wrapper for function call that delays the actual execution so that :py:func:`~hamcrest.core.core.raises.raises` matcher can catch any thrown exception. :param func: The function or method to be called The arguments can be provided with a call to the `with_args` function on the returned object:: calling(my_method).with_args(arguments, and_='keywords') """ return DeferredCallable(func) PyHamcrest-1.9.0/src/hamcrest/core/description.py000066400000000000000000000033011266666136400220370ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class Description(object): """A description of a :py:class:`~hamcrest.core.matcher.Matcher`. A :py:class:`~hamcrest.core.matcher.Matcher` will describe itself to a description which can later be used for reporting. """ def append_text(self, text): """Appends some plain text to the description. :returns: ``self``, for chaining """ raise NotImplementedError('append_text') def append_description_of(self, value): """Appends description of given value to this description. If the value implements :py:meth:`~hamcrest.core.selfdescribing.SelfDescribing.describe_to`, then it will be used. :returns: ``self``, for chaining """ raise NotImplementedError('append_description_of') def append_value(self, value): """Appends an arbitary value to the description. **Deprecated:** Call :py:meth:`~hamcrest.core.description.Description.append_description_of` instead. :returns: ``self``, for chaining """ raise NotImplementedError('append_value') def append_list(self, start, separator, end, list): """Appends a list of objects to the description. :param start: String that will begin the list description. :param separator: String that will separate each object in the description. :param end: String that will end the list description. :param list: List of objects to be described. :returns: ``self``, for chaining """ raise NotImplementedError('append_list') PyHamcrest-1.9.0/src/hamcrest/core/helpers/000077500000000000000000000000001266666136400206075ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/core/helpers/__init__.py000066400000000000000000000002221266666136400227140ustar00rootroot00000000000000"""Utilities for writing Matchers.""" __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/core/helpers/hasmethod.py000066400000000000000000000005051266666136400231350ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" def hasmethod(obj, methodname): """Does ``obj`` have a method named ``methodname``?""" if not hasattr(obj, methodname): return False method = getattr(obj, methodname) return callable(method) PyHamcrest-1.9.0/src/hamcrest/core/helpers/wrap_matcher.py000066400000000000000000000015601266666136400236370ustar00rootroot00000000000000import six from hamcrest.core.base_matcher import Matcher from hamcrest.core.core.isequal import equal_to __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import types def wrap_matcher(x): """Wraps argument in a matcher, if necessary. :returns: the argument as-is if it is already a matcher, otherwise wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher. """ if isinstance(x, Matcher): return x else: return equal_to(x) def is_matchable_type(expected_type): if isinstance(expected_type, type): return True if isinstance(expected_type, six.class_types): return True if isinstance(expected_type, tuple) and \ expected_type and \ all(map(is_matchable_type, expected_type)): return True return False PyHamcrest-1.9.0/src/hamcrest/core/matcher.py000066400000000000000000000034731266666136400211510ustar00rootroot00000000000000from __future__ import absolute_import from .selfdescribing import SelfDescribing __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class Matcher(SelfDescribing): """A matcher over acceptable values. A matcher is able to describe itself to give feedback when it fails. Matcher implementations should *not* directly implement this protocol. Instead, *extend* the :py:class:`~hamcrest.core.base_matcher.BaseMatcher` class, which will ensure that the :py:class:`~hamcrest.core.matcher.Matcher` API can grow to support new features and remain compatible with all :py:class:`~hamcrest.core.matcher.Matcher` implementations. """ def matches(self, item, mismatch_description=None): """Evaluates the matcher for argument item. If a mismatch is detected and argument ``mismatch_description`` is provided, it will generate a description of why the matcher has not accepted the item. :param item: The object against which the matcher is evaluated. :returns: ``True`` if ``item`` matches, otherwise ``False``. """ raise NotImplementedError('matches') def describe_mismatch(self, item, mismatch_description): """Generates a description of why the matcher has not accepted the item. The description will be part of a larger description of why a matching failed, so it should be concise. This method assumes that ``matches(item)`` is ``False``, but will not check this. :param item: The item that the :py:class:`~hamcrest.core.matcher.Matcher` has rejected. :param mismatch_description: The description to be built or appended to. """ raise NotImplementedError('describe_mismatch') PyHamcrest-1.9.0/src/hamcrest/core/selfdescribing.py000066400000000000000000000010761266666136400225060ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class SelfDescribing(object): """The ability of an object to describe itself.""" def describe_to(self, description): """Generates a description of the object. The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately. :param description: The description to be built or appended to. """ raise NotImplementedError('describe_to') PyHamcrest-1.9.0/src/hamcrest/core/selfdescribingvalue.py000066400000000000000000000015021266666136400235350ustar00rootroot00000000000000from hamcrest.core.selfdescribing import SelfDescribing import warnings __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class SelfDescribingValue(SelfDescribing): """Wrap any value in a ``SelfDescribingValue`` to satisfy the :py:class:`~hamcrest.core.selfdescribing.SelfDescribing` interface. **Deprecated:** No need for this class now that :py:meth:`~hamcrest.core.description.Description.append_description_of` handles any type of value. """ def __init__(self, value): warnings.warn('SelfDescribingValue no longer needed', DeprecationWarning) self.value = value def describe_to(self, description): """Generates a description of the value.""" description.append_value(self.value) PyHamcrest-1.9.0/src/hamcrest/core/string_description.py000066400000000000000000000016141266666136400234320ustar00rootroot00000000000000from __future__ import absolute_import import codecs import six from .base_description import BaseDescription __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" def tostring(selfdescribing): """Returns the description of a :py:class:`~hamcrest.core.selfdescribing.SelfDescribing` object as a string. :param selfdescribing: The object to be described. :returns: The description of the object. """ return str(StringDescription().append_description_of(selfdescribing)) class StringDescription(BaseDescription): """A :py:class:`~hamcrest.core.description.Description` that is stored as a string. """ def __init__(self): self.out = '' def __str__(self): """Returns the description.""" return self.out def append(self, string): self.out += six.text_type(string) PyHamcrest-1.9.0/src/hamcrest/library/000077500000000000000000000000001266666136400176615ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/library/__init__.py000066400000000000000000000017661266666136400220040ustar00rootroot00000000000000from __future__ import absolute_import """Library of Matcher implementations.""" from hamcrest.core import * from hamcrest.library.collection import * from hamcrest.library.integration import * from hamcrest.library.number import * from hamcrest.library.object import * from hamcrest.library.text import * __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" __all__ = [ 'has_entry', 'has_entries', 'has_key', 'has_value', 'is_in', 'empty', 'has_item', 'has_items', 'contains_inanyorder', 'contains', 'only_contains', 'match_equality', 'matches_regexp', 'close_to', 'greater_than', 'greater_than_or_equal_to', 'less_than', 'less_than_or_equal_to', 'has_length', 'has_property', 'has_properties', 'has_string', 'equal_to_ignoring_case', 'equal_to_ignoring_whitespace', 'contains_string', 'ends_with', 'starts_with', 'string_contains_in_order', ] PyHamcrest-1.9.0/src/hamcrest/library/collection/000077500000000000000000000000001266666136400220145ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/library/collection/__init__.py000066400000000000000000000011731266666136400241270ustar00rootroot00000000000000"""Matchers of collections.""" from __future__ import absolute_import from .isdict_containing import has_entry from .isdict_containingentries import has_entries from .isdict_containingkey import has_key from .isdict_containingvalue import has_value from .isin import is_in from .issequence_containing import has_item, has_items from .issequence_containinginanyorder import contains_inanyorder from .issequence_containinginorder import contains from .issequence_onlycontaining import only_contains from .is_empty import empty __author__ = "Chris Rose" __copyright__ = "Copyright 2013 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/library/collection/is_empty.py000066400000000000000000000016211266666136400242170ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher __author__ = "Chris Rose" __copyright__ = "Copyright 2012 hamcrest.org" __license__ = "BSD, see License.txt" class IsEmpty(BaseMatcher): def matches(self, item, mismatch_description=None): try: if len(item) == 0: return True if mismatch_description: mismatch_description \ .append_text('has %d item(s)' % len(item)) except TypeError: if mismatch_description: mismatch_description \ .append_text('does not support length') return False def describe_to(self, description): description.append_text('an empty collection') def empty(): """ This matcher matches any collection-like object that responds to the __len__ method, and has a length of 0. """ return IsEmpty() PyHamcrest-1.9.0/src/hamcrest/library/collection/isdict_containing.py000066400000000000000000000040101266666136400260510ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContaining(BaseMatcher): def __init__(self, key_matcher, value_matcher): self.key_matcher = key_matcher self.value_matcher = value_matcher def _matches(self, dictionary): if hasmethod(dictionary, 'items'): for key, value in dictionary.items(): if self.key_matcher.matches(key) and self.value_matcher.matches(value): return True return False def describe_to(self, description): description.append_text('a dictionary containing [') \ .append_description_of(self.key_matcher) \ .append_text(': ') \ .append_description_of(self.value_matcher) \ .append_text(']') def has_entry(key_match, value_match): """Matches if dictionary contains key-value entry satisfying a given pair of matchers. :param key_match: The matcher to satisfy for the key, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. :param value_match: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher iterates the evaluated dictionary, searching for any key-value entry that satisfies ``key_match`` and ``value_match``. If a matching entry is found, ``has_entry`` is satisfied. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_entry(equal_to('foo'), equal_to(1)) has_entry('foo', 1) """ return IsDictContaining(wrap_matcher(key_match), wrap_matcher(value_match)) PyHamcrest-1.9.0/src/hamcrest/library/collection/isdict_containingentries.py000066400000000000000000000120601266666136400274470ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingEntries(BaseMatcher): def __init__(self, value_matchers): self.value_matchers = sorted(value_matchers.items()) def _not_a_dictionary(self, dictionary, mismatch_description): if mismatch_description: mismatch_description.append_description_of(dictionary) \ .append_text(' is not a mapping object') return False def matches(self, dictionary, mismatch_description=None): for key, value_matcher in self.value_matchers: try: if not key in dictionary: if mismatch_description: mismatch_description.append_text('no ') \ .append_description_of(key) \ .append_text(' key in ') \ .append_description_of(dictionary) return False except TypeError: return self._not_a_dictionary(dictionary, mismatch_description) try: actual_value = dictionary[key] except TypeError: return self._not_a_dictionary(dictionary, mismatch_description) if not value_matcher.matches(actual_value): if mismatch_description: mismatch_description.append_text('value for ') \ .append_description_of(key) \ .append_text(' ') value_matcher.describe_mismatch(actual_value, mismatch_description) return False return True def describe_mismatch(self, item, mismatch_description): self.matches(item, mismatch_description) def describe_keyvalue(self, index, value, description): """Describes key-value pair at given index.""" description.append_description_of(index) \ .append_text(': ') \ .append_description_of(value) def describe_to(self, description): description.append_text('a dictionary containing {') first = True for key, value in self.value_matchers: if not first: description.append_text(', ') self.describe_keyvalue(key, value, description) first = False description.append_text('}') def has_entries(*keys_valuematchers, **kv_args): """Matches if dictionary contains entries satisfying a dictionary of keys and corresponding value matchers. :param matcher_dict: A dictionary mapping keys to associated value matchers, or to expected values for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Note that the keys must be actual keys, not matchers. Any value argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_entries({'foo':equal_to(1), 'bar':equal_to(2)}) has_entries({'foo':1, 'bar':2}) ``has_entries`` also accepts a list of keyword arguments: .. function:: has_entries(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]]) :param keyword1: A keyword to look up. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_entries(foo=equal_to(1), bar=equal_to(2)) has_entries(foo=1, bar=2) Finally, ``has_entries`` also accepts a list of alternating keys and their value matchers: .. function:: has_entries(key1, value_matcher1[, ...]) :param key1: A key (not a matcher) to look up. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_entries('foo', equal_to(1), 'bar', equal_to(2)) has_entries('foo', 1, 'bar', 2) """ if len(keys_valuematchers) == 1: try: base_dict = keys_valuematchers[0].copy() for key in base_dict: base_dict[key] = wrap_matcher(base_dict[key]) except AttributeError: raise ValueError('single-argument calls to has_entries must pass a dict as the argument') else: if len(keys_valuematchers) % 2: raise ValueError('has_entries requires key-value pairs') base_dict = {} for index in range(int(len(keys_valuematchers) / 2)): base_dict[keys_valuematchers[2 * index]] = wrap_matcher(keys_valuematchers[2 * index + 1]) for key, value in kv_args.items(): base_dict[key] = wrap_matcher(value) return IsDictContainingEntries(base_dict) PyHamcrest-1.9.0/src/hamcrest/library/collection/isdict_containingkey.py000066400000000000000000000027771266666136400266040ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingKey(BaseMatcher): def __init__(self, key_matcher): self.key_matcher = key_matcher def _matches(self, dictionary): if hasmethod(dictionary, 'keys'): for key in dictionary.keys(): if self.key_matcher.matches(key): return True return False def describe_to(self, description): description.append_text('a dictionary containing key ') \ .append_description_of(self.key_matcher) def has_key(key_match): """Matches if dictionary contains an entry whose key satisfies a given matcher. :param key_match: The matcher to satisfy for the key, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher iterates the evaluated dictionary, searching for any key-value entry whose key satisfies the given matcher. If a matching entry is found, ``has_key`` is satisfied. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_key(equal_to('foo')) has_key('foo') """ return IsDictContainingKey(wrap_matcher(key_match)) PyHamcrest-1.9.0/src/hamcrest/library/collection/isdict_containingvalue.py000066400000000000000000000030351266666136400271140ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingValue(BaseMatcher): def __init__(self, value_matcher): self.value_matcher = value_matcher def _matches(self, dictionary): if hasmethod(dictionary, 'values'): for value in dictionary.values(): if self.value_matcher.matches(value): return True return False def describe_to(self, description): description.append_text('a dictionary containing value ') \ .append_description_of(self.value_matcher) def has_value(value): """Matches if dictionary contains an entry whose value satisfies a given matcher. :param value_match: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher iterates the evaluated dictionary, searching for any key-value entry whose value satisfies the given matcher. If a matching entry is found, ``has_value`` is satisfied. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_value(equal_to('bar')) has_value('bar') """ return IsDictContainingValue(wrap_matcher(value)) PyHamcrest-1.9.0/src/hamcrest/library/collection/isin.py000066400000000000000000000014061266666136400233310ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsIn(BaseMatcher): def __init__(self, sequence): self.sequence = sequence def _matches(self, item): return item in self.sequence def describe_to(self, description): description.append_text('one of ') \ .append_list('(', ', ', ')', self.sequence) def is_in(sequence): """Matches if evaluated object is present in a given sequence. :param sequence: The sequence to search. This matcher invokes the ``in`` membership operator to determine if the evaluated object is a member of the sequence. """ return IsIn(sequence) PyHamcrest-1.9.0/src/hamcrest/library/collection/issequence_containing.py000066400000000000000000000056711266666136400267540ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.core.allof import all_of from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher class IsSequenceContaining(BaseMatcher): def __init__(self, element_matcher): self.element_matcher = element_matcher def _matches(self, sequence): try: for item in sequence: if self.element_matcher.matches(item): return True except TypeError: # not a sequence return False def describe_to(self, description): description.append_text('a sequence containing ') \ .append_description_of(self.element_matcher) # It'd be great to make use of all_of, but we can't be sure we won't # be seeing a one-time sequence here (like a generator); see issue #20 # Instead, we wrap it inside a class that will convert the sequence into # a concrete list and then hand it off to the all_of matcher. class IsSequenceContainingEvery(BaseMatcher): def __init__(self, *element_matchers): delegates = [has_item(e) for e in element_matchers] self.matcher = all_of(*delegates) def _matches(self, sequence): try: return self.matcher.matches(list(sequence)) except TypeError: return False def describe_mismatch(self, item, mismatch_description): self.matcher.describe_mismatch(item, mismatch_description) def describe_to(self, description): self.matcher.describe_to(description) def has_item(match): """Matches if any element of sequence satisfies a given matcher. :param match: The matcher to satisfy, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher iterates the evaluated sequence, searching for any element that satisfies a given matcher. If a matching element is found, ``has_item`` is satisfied. If the ``match`` argument is not a matcher, it is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ return IsSequenceContaining(wrap_matcher(match)) def has_items(*items): """Matches if all of the given matchers are satisfied by any elements of the sequence. :param match1,...: A comma-separated list of matchers. This matcher iterates the given matchers, searching for any elements in the evaluated sequence that satisfy them. If each matcher is satisfied, then ``has_items`` is satisfied. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceContainingEvery(*matchers) PyHamcrest-1.9.0/src/hamcrest/library/collection/issequence_containinginanyorder.py000066400000000000000000000070351266666136400310430ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class MatchInAnyOrder(object): def __init__(self, matchers, mismatch_description): self.matchers = matchers[:] self.mismatch_description = mismatch_description def matches(self, item): return self.isnotsurplus(item) and self.ismatched(item) def isfinished(self, sequence): if not self.matchers: return True if self.mismatch_description: self.mismatch_description.append_text('no item matches: ') \ .append_list('', ', ', '', self.matchers) \ .append_text(' in ') \ .append_list('[', ', ', ']', sequence) return False def isnotsurplus(self, item): if not self.matchers: if self.mismatch_description: self.mismatch_description.append_text('not matched: ') \ .append_description_of(item) return False return True def ismatched(self, item): for index, matcher in enumerate(self.matchers): if matcher.matches(item): del self.matchers[index] return True if self.mismatch_description: self.mismatch_description.append_text('not matched: ') \ .append_description_of(item) return False class IsSequenceContainingInAnyOrder(BaseMatcher): def __init__(self, matchers): self.matchers = matchers def matches(self, sequence, mismatch_description=None): try: sequence = list(sequence) matchsequence = MatchInAnyOrder(self.matchers, mismatch_description) for item in sequence: if not matchsequence.matches(item): return False return matchsequence.isfinished(sequence) except TypeError: if mismatch_description: super(IsSequenceContainingInAnyOrder, self) \ .describe_mismatch(sequence, mismatch_description) return False def describe_mismatch(self, item, mismatch_description): self.matches(item, mismatch_description) def describe_to(self, description): description.append_text('a sequence over ') \ .append_list('[', ', ', ']', self.matchers) \ .append_text(' in any order') def contains_inanyorder(*items): """Matches if sequences's elements, in any order, satisfy a given list of matchers. :param match1,...: A comma-separated list of matchers. This matcher iterates the evaluated sequence, seeing if each element satisfies any of the given matchers. The matchers are tried from left to right, and when a satisfied matcher is found, it is no longer a candidate for the remaining elements. If a one-to-one correspondence is established between elements and matchers, ``contains_inanyorder`` is satisfied. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceContainingInAnyOrder(matchers) PyHamcrest-1.9.0/src/hamcrest/library/collection/issequence_containinginorder.py000066400000000000000000000062231266666136400303310ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher class MatchingInOrder(object): def __init__(self, matchers, mismatch_description): self.matchers = matchers self.mismatch_description = mismatch_description self.next_match_index = 0 def matches(self, item): return self.isnotsurplus(item) and self.ismatched(item) def isfinished(self): if self.next_match_index < len(self.matchers): if self.mismatch_description: self.mismatch_description.append_text('No item matched: ') \ .append_description_of(self.matchers[self.next_match_index]) return False return True def ismatched(self, item): matcher = self.matchers[self.next_match_index] if not matcher.matches(item): if self.mismatch_description: self.mismatch_description.append_text('item ' + str(self.next_match_index) + ': ') matcher.describe_mismatch(item, self.mismatch_description) return False self.next_match_index += 1 return True def isnotsurplus(self, item): if len(self.matchers) <= self.next_match_index: if self.mismatch_description: self.mismatch_description.append_text('Not matched: ') \ .append_description_of(item) return False return True class IsSequenceContainingInOrder(BaseMatcher): def __init__(self, matchers): self.matchers = matchers def matches(self, sequence, mismatch_description=None): try: matchsequence = MatchingInOrder(self.matchers, mismatch_description) for item in sequence: if not matchsequence.matches(item): return False return matchsequence.isfinished() except TypeError: if mismatch_description: super(IsSequenceContainingInOrder, self) \ .describe_mismatch(sequence, mismatch_description) return False def describe_mismatch(self, item, mismatch_description): self.matches(item, mismatch_description) def describe_to(self, description): description.append_text('a sequence containing ') \ .append_list('[', ', ', ']', self.matchers) def contains(*items): """Matches if sequence's elements satisfy a given list of matchers, in order. :param match1,...: A comma-separated list of matchers. 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 :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceContainingInOrder(matchers) PyHamcrest-1.9.0/src/hamcrest/library/collection/issequence_onlycontaining.py000066400000000000000000000031321266666136400276440ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.core.anyof import any_of from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsSequenceOnlyContaining(BaseMatcher): def __init__(self, matcher): self.matcher = matcher def _matches(self, sequence): try: sequence = list(sequence) if len(sequence) == 0: return False for item in sequence: if not self.matcher.matches(item): return False return True except TypeError: return False def describe_to(self, description): description.append_text('a sequence containing items matching ') \ .append_description_of(self.matcher) def only_contains(*items): """Matches if each element of sequence satisfies any of the given matchers. :param match1,...: A comma-separated list of matchers. This matcher iterates the evaluated sequence, confirming whether each element satisfies any of the given matchers. Example:: only_contains(less_than(4)) will match ``[3,1,2]``. Any argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. """ matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceOnlyContaining(any_of(*matchers)) PyHamcrest-1.9.0/src/hamcrest/library/integration/000077500000000000000000000000001266666136400222045ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/library/integration/__init__.py000066400000000000000000000003761266666136400243230ustar00rootroot00000000000000from __future__ import absolute_import """Utilities for integrating Hamcrest with other libraries.""" from .match_equality import match_equality __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/library/integration/match_equality.py000066400000000000000000000022501266666136400255660ustar00rootroot00000000000000from hamcrest.core.string_description import tostring from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Chris Rose" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" __unittest = True class EqualityWrapper(object): def __init__(self, matcher): self.matcher = matcher def __eq__(self, object): return self.matcher.matches(object) def __str__(self): return repr(self) def __repr__(self): return tostring(self.matcher) def match_equality(matcher): """Wraps a matcher to define equality in terms of satisfying the matcher. ``match_equality`` allows Hamcrest matchers to be used in libraries that are not Hamcrest-aware. They might use the equality operator:: assert match_equality(matcher) == object Or they might provide a method that uses equality for its test:: library.method_that_tests_eq(match_equality(matcher)) One concrete example is integrating with the ``assert_called_with`` methods in Michael Foord's `mock `_ library. """ return EqualityWrapper(wrap_matcher(matcher)) PyHamcrest-1.9.0/src/hamcrest/library/number/000077500000000000000000000000001266666136400211515ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/library/number/__init__.py000066400000000000000000000005171266666136400232650ustar00rootroot00000000000000from __future__ import absolute_import """Matchers that perform numeric comparisons.""" from .iscloseto import close_to from .ordering_comparison import greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/library/number/iscloseto.py000066400000000000000000000043231266666136400235310ustar00rootroot00000000000000import six from hamcrest.core.base_matcher import BaseMatcher from math import fabs __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" def isnumeric(value): """Confirm that 'value' can be treated numerically; duck-test accordingly """ if isinstance(value, (float, complex) + six.integer_types): return True try: _ = (fabs(value) + 0 - 0) * 1 return True except ArithmeticError: return True except: return False return False class IsCloseTo(BaseMatcher): def __init__(self, value, delta): if not isnumeric(value): raise TypeError('IsCloseTo value must be numeric') if not isnumeric(delta): raise TypeError('IsCloseTo delta must be numeric') self.value = value self.delta = delta def _matches(self, item): if not isnumeric(item): return False return fabs(item - self.value) <= self.delta def describe_mismatch(self, item, mismatch_description): if not isnumeric(item): super(IsCloseTo, self).describe_mismatch(item, mismatch_description) else: actual_delta = fabs(item - self.value) mismatch_description.append_description_of(item) \ .append_text(' differed by ') \ .append_description_of(actual_delta) def describe_to(self, description): description.append_text('a numeric value within ') \ .append_description_of(self.delta) \ .append_text(' of ') \ .append_description_of(self.value) def close_to(value, delta): """Matches if object is a number close to a given value, within a given delta. :param value: The value to compare against as the expected value. :param delta: The maximum delta between the values for which the numbers are considered close. This matcher compares the evaluated object against ``value`` to see if the difference is within a positive ``delta``. Example:: close_to(3.0, 0.25) """ return IsCloseTo(value, delta) PyHamcrest-1.9.0/src/hamcrest/library/number/ordering_comparison.py000066400000000000000000000032441266666136400255710ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher import operator __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class OrderingComparison(BaseMatcher): def __init__(self, value, comparison_function, comparison_description): self.value = value self.comparison_function = comparison_function self.comparison_description = comparison_description def _matches(self, item): return self.comparison_function(item, self.value) def describe_to(self, description): description.append_text('a value ') \ .append_text(self.comparison_description) \ .append_text(' ') \ .append_description_of(self.value) def greater_than(value): """Matches if object is greater than a given value. :param value: The value to compare against. """ return OrderingComparison(value, operator.gt, 'greater than') def greater_than_or_equal_to(value): """Matches if object is greater than or equal to a given value. :param value: The value to compare against. """ return OrderingComparison(value, operator.ge, 'greater than or equal to') def less_than(value): """Matches if object is less than a given value. :param value: The value to compare against. """ return OrderingComparison(value, operator.lt, 'less than') def less_than_or_equal_to(value): """Matches if object is less than or equal to a given value. :param value: The value to compare against. """ return OrderingComparison(value, operator.le, 'less than or equal to') PyHamcrest-1.9.0/src/hamcrest/library/object/000077500000000000000000000000001266666136400211275ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/library/object/__init__.py000066400000000000000000000004771266666136400232500ustar00rootroot00000000000000from __future__ import absolute_import """Matchers that inspect objects and classes.""" from .haslength import has_length from .hasproperty import has_property, has_properties from .hasstring import has_string __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/library/object/haslength.py000066400000000000000000000032211266666136400234540ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class HasLength(BaseMatcher): def __init__(self, len_matcher): self.len_matcher = len_matcher def _matches(self, item): if not hasmethod(item, '__len__'): return False return self.len_matcher.matches(len(item)) def describe_mismatch(self, item, mismatch_description): super(HasLength, self).describe_mismatch(item, mismatch_description) if hasmethod(item, '__len__'): mismatch_description.append_text(' with length of ') \ .append_description_of(len(item)) def describe_to(self, description): description.append_text('an object with length of ') \ .append_description_of(self.len_matcher) def has_length(match): """Matches if ``len(item)`` satisfies a given matcher. :param match: The matcher to satisfy, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher invokes the :py:func:`len` function on the evaluated object to get its length, passing the result to a given matcher for evaluation. If the ``match`` argument is not a matcher, it is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for :equality. Examples:: has_length(greater_than(6)) has_length(5) """ return HasLength(wrap_matcher(match)) PyHamcrest-1.9.0/src/hamcrest/library/object/hasproperty.py000066400000000000000000000131541266666136400240650ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core import anything from hamcrest.core.core.allof import all_of from hamcrest.core.string_description import StringDescription from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher as wrap_shortcut __author__ = "Chris Rose" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsObjectWithProperty(BaseMatcher): def __init__(self, property_name, value_matcher): self.property_name = property_name self.value_matcher = value_matcher def _matches(self, o): if o is None: return False if not hasattr(o, self.property_name): return False value = getattr(o, self.property_name) return self.value_matcher.matches(value) def describe_to(self, description): description.append_text("an object with a property '") \ .append_text(self.property_name) \ .append_text("' matching ") \ .append_description_of(self.value_matcher) def describe_mismatch(self, item, mismatch_description): if item is None: mismatch_description.append_text('was None') return if not hasattr(item, self.property_name): mismatch_description.append_value(item) \ .append_text(' did not have the ') \ .append_value(self.property_name) \ .append_text(' property') return mismatch_description.append_text('property ').append_value(self.property_name).append_text(' ') value = getattr(item, self.property_name) self.value_matcher.describe_mismatch(value, mismatch_description) def __str__(self): d = StringDescription() self.describe_to(d) return str(d) def has_property(name, match=None): """Matches if object has a property with a given name whose value satisfies a given matcher. :param name: The name of the property. :param match: Optional matcher to satisfy. This matcher determines if the evaluated object has a property with a given name. If no such property is found, ``has_property`` is not satisfied. If the property is found, its value is passed to a given matcher for evaluation. If the ``match`` argument is not a matcher, it is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. If the ``match`` argument is not provided, the :py:func:`~hamcrest.core.core.isanything.anything` matcher is used so that ``has_property`` is satisfied if a matching property is found. Examples:: has_property('name', starts_with('J')) has_property('name', 'Jon') has_property('name') """ if match is None: match = anything() return IsObjectWithProperty(name, wrap_shortcut(match)) def has_properties(*keys_valuematchers, **kv_args): """Matches if an object has properties satisfying all of a dictionary of string property names and corresponding value matchers. :param matcher_dict: A dictionary mapping keys to associated value matchers, or to expected values for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Note that the keys must be actual keys, not matchers. Any value argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_properties({'foo':equal_to(1), 'bar':equal_to(2)}) has_properties({'foo':1, 'bar':2}) ``has_properties`` also accepts a list of keyword arguments: .. function:: has_properties(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]]) :param keyword1: A keyword to look up. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_properties(foo=equal_to(1), bar=equal_to(2)) has_properties(foo=1, bar=2) Finally, ``has_properties`` also accepts a list of alternating keys and their value matchers: .. function:: has_properties(key1, value_matcher1[, ...]) :param key1: A key (not a matcher) to look up. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_properties('foo', equal_to(1), 'bar', equal_to(2)) has_properties('foo', 1, 'bar', 2) """ if len(keys_valuematchers) == 1: try: base_dict = keys_valuematchers[0].copy() for key in base_dict: base_dict[key] = wrap_shortcut(base_dict[key]) except AttributeError: raise ValueError('single-argument calls to has_properties must pass a dict as the argument') else: if len(keys_valuematchers) % 2: raise ValueError('has_properties requires key-value pairs') base_dict = {} for index in range(int(len(keys_valuematchers) / 2)): base_dict[keys_valuematchers[2 * index]] = wrap_shortcut(keys_valuematchers[2 * index + 1]) for key, value in kv_args.items(): base_dict[key] = wrap_shortcut(value) return all_of(*[has_property(property_name, property_value_matcher) for \ property_name, property_value_matcher in base_dict.items()]) PyHamcrest-1.9.0/src/hamcrest/library/object/hasstring.py000066400000000000000000000023421266666136400235040ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class HasString(BaseMatcher): def __init__(self, str_matcher): self.str_matcher = str_matcher def _matches(self, item): return self.str_matcher.matches(str(item)) def describe_to(self, description): description.append_text('an object with str ') \ .append_description_of(self.str_matcher) def has_string(match): """Matches if ``str(item)`` satisfies a given matcher. :param match: The matcher to satisfy, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. This matcher invokes the :py:func:`str` function on the evaluated object to get its length, passing the result to a given matcher for evaluation. If the ``match`` argument is not a matcher, it is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_string(starts_with('foo')) has_string('bar') """ return HasString(wrap_matcher(match)) PyHamcrest-1.9.0/src/hamcrest/library/text/000077500000000000000000000000001266666136400206455ustar00rootroot00000000000000PyHamcrest-1.9.0/src/hamcrest/library/text/__init__.py000066400000000000000000000010441266666136400227550ustar00rootroot00000000000000from __future__ import absolute_import """Matchers that perform text comparisons.""" from .isequal_ignoring_case import equal_to_ignoring_case from .isequal_ignoring_whitespace import equal_to_ignoring_whitespace from .stringcontains import contains_string from .stringendswith import ends_with from .stringstartswith import starts_with from .stringmatches import matches_regexp from .stringcontainsinorder import string_contains_in_order __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" PyHamcrest-1.9.0/src/hamcrest/library/text/isequal_ignoring_case.py000066400000000000000000000023511266666136400255520ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher import six class IsEqualIgnoringCase(BaseMatcher): def __init__(self, string): if not isinstance(string, six.string_types): raise TypeError('IsEqualIgnoringCase requires string') self.original_string = string self.lowered_string = string.lower() def _matches(self, item): if not isinstance(item, six.string_types): return False return self.lowered_string == item.lower() def describe_to(self, description): description.append_description_of(self.original_string) \ .append_text(' ignoring case') def equal_to_ignoring_case(string): """Matches if object is a string equal to a given string, ignoring case differences. :param string: The string to compare against as the expected value. This matcher first checks whether the evaluated object is a string. If so, it compares it with ``string``, ignoring differences of case. Example:: equal_to_ignoring_case("hello world") will match "heLLo WorlD". """ return IsEqualIgnoringCase(string) PyHamcrest-1.9.0/src/hamcrest/library/text/isequal_ignoring_whitespace.py000066400000000000000000000032031266666136400267700ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher import six def stripspace(string): result = '' last_was_space = True for character in string: if character.isspace(): if not last_was_space: result += ' ' last_was_space = True else: result += character last_was_space = False return result.strip() class IsEqualIgnoringWhiteSpace(BaseMatcher): def __init__(self, string): if not isinstance(string, six.string_types): raise TypeError('IsEqualIgnoringWhiteSpace requires string') self.original_string = string self.stripped_string = stripspace(string) def _matches(self, item): if not isinstance(item, six.string_types): return False return self.stripped_string == stripspace(item) def describe_to(self, description): description.append_description_of(self.original_string) \ .append_text(' ignoring whitespace') def equal_to_ignoring_whitespace(string): """Matches if object is a string equal to a given string, ignoring differences in whitespace. :param string: The string to compare against as the expected value. This matcher first checks whether the evaluated object is a string. If so, it compares it with ``string``, ignoring differences in runs of whitespace. Example:: equal_to_ignoring_whitespace("hello world") will match ``"hello world"``. """ return IsEqualIgnoringWhiteSpace(string) PyHamcrest-1.9.0/src/hamcrest/library/text/stringcontains.py000066400000000000000000000016711266666136400242710ustar00rootroot00000000000000from hamcrest.library.text.substringmatcher import SubstringMatcher from hamcrest.core.helpers.hasmethod import hasmethod __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class StringContains(SubstringMatcher): def __init__(self, substring): super(StringContains, self).__init__(substring) def _matches(self, item): if not hasmethod(item, 'find'): return False return item.find(self.substring) >= 0 def relationship(self): return 'containing' def contains_string(substring): """Matches if object is a string containing a given string. :param string: The string to search for. This matcher first checks whether the evaluated object is a string. If so, it checks whether it contains ``string``. Example:: contains_string("def") will match "abcdefg". """ return StringContains(substring) PyHamcrest-1.9.0/src/hamcrest/library/text/stringcontainsinorder.py000066400000000000000000000032511266666136400256500ustar00rootroot00000000000000__author__ = "Romilly Cocking" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod import six class StringContainsInOrder(BaseMatcher): def __init__(self, *substrings): for substring in substrings: if not isinstance(substring, six.string_types): raise TypeError(self.__class__.__name__ + ' requires string arguments') self.substrings = substrings def _matches(self, item): if not hasmethod(item, 'find'): return False from_index = 0 for substring in self.substrings: from_index = item.find(substring, from_index) if from_index == -1: return False return True def describe_to(self, description): description.append_list('a string containing ', ', ', ' in order', self.substrings) def string_contains_in_order(*substrings): """Matches if object is a string containing a given list of substrings in relative order. :param string1,...: A comma-separated list of strings. This matcher first checks whether the evaluated object is a string. If so, it checks whether it contains a given list of strings, in relative order to each other. The searches are performed starting from the beginning of the evaluated string. Example:: string_contains_in_order("bc", "fg", "jkl") will match "abcdefghijklm". """ return StringContainsInOrder(*substrings) PyHamcrest-1.9.0/src/hamcrest/library/text/stringendswith.py000066400000000000000000000017241266666136400242770ustar00rootroot00000000000000from hamcrest.library.text.substringmatcher import SubstringMatcher from hamcrest.core.helpers.hasmethod import hasmethod __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class StringEndsWith(SubstringMatcher): def __init__(self, substring): super(StringEndsWith, self).__init__(substring) def _matches(self, item): if not hasmethod(item, 'endswith'): return False return item.endswith(self.substring) def relationship(self): return 'ending with' def ends_with(string): """Matches if object is a string ending with a given string. :param string: The string to search for. This matcher first checks whether the evaluated object is a string. If so, it checks if ``string`` matches the ending characters of the evaluated object. Example:: ends_with("bar") will match "foobar". """ return StringEndsWith(string) PyHamcrest-1.9.0/src/hamcrest/library/text/stringmatches.py000066400000000000000000000021771266666136400241010ustar00rootroot00000000000000__author__ = "Chris Rose" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import re import six from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod class StringMatchesPattern(BaseMatcher): def __init__(self, pattern): self.pattern = pattern def describe_to(self, description): description.append_text("a string matching '") \ .append_text(self.pattern.pattern) \ .append_text("'") def _matches(self, item): return self.pattern.search(item) is not None def matches_regexp(pattern): """Matches if object is a string containing a match for a given regular expression. :param pattern: The regular expression to search for. This matcher first checks whether the evaluated object is a string. If so, it checks if the regular expression ``pattern`` matches anywhere within the evaluated object. """ if isinstance(pattern, six.string_types): pattern = re.compile(pattern) return StringMatchesPattern(pattern) PyHamcrest-1.9.0/src/hamcrest/library/text/stringstartswith.py000066400000000000000000000017571266666136400246740ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.library.text.substringmatcher import SubstringMatcher from hamcrest.core.helpers.hasmethod import hasmethod class StringStartsWith(SubstringMatcher): def __init__(self, substring): super(StringStartsWith, self).__init__(substring) def _matches(self, item): if not hasmethod(item, 'startswith'): return False return item.startswith(self.substring) def relationship(self): return 'starting with' def starts_with(substring): """Matches if object is a string starting with a given string. :param string: The string to search for. This matcher first checks whether the evaluated object is a string. If so, it checks if ``string`` matches the beginning characters of the evaluated object. Example:: starts_with("foo") will match "foobar". """ return StringStartsWith(substring) PyHamcrest-1.9.0/src/hamcrest/library/text/substringmatcher.py000066400000000000000000000012671266666136400246110ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" from hamcrest.core.base_matcher import BaseMatcher import six class SubstringMatcher(BaseMatcher): def __init__(self, substring): if not isinstance(substring, six.string_types): raise TypeError(self.__class__.__name__ + ' requires string') self.substring = substring def describe_to(self, description): description.append_text('a string ') \ .append_text(self.relationship()) \ .append_text(' ') \ .append_description_of(self.substring) PyHamcrest-1.9.0/tests/000077500000000000000000000000001266666136400147625ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/000077500000000000000000000000001266666136400206665ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/__init__.py000066400000000000000000000000021266666136400227670ustar00rootroot00000000000000# PyHamcrest-1.9.0/tests/hamcrest_unit_test/assert_that_test.py000066400000000000000000000041771266666136400246310ustar00rootroot00000000000000# encoding: utf-8 from __future__ import with_statement from hamcrest.core.assert_that import assert_that from hamcrest.core.core.isequal import equal_to try: import unittest2 as unittest except ImportError: import unittest import sys if sys.version < '3': import codecs def u(x): return codecs.unicode_escape_decode(x)[0] else: def u(x): return x __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class AssertThatTest(unittest.TestCase): def testShouldBeSilentOnSuccessfulMatch(self): assert_that(1, equal_to(1)) def testAssertionErrorShouldDescribeExpectedAndActual(self): expected = 'EXPECTED' actual = 'ACTUAL' expectedMessage = "\nExpected: 'EXPECTED'\n but: was 'ACTUAL'\n" with self.assertRaises(AssertionError) as e: assert_that(actual, equal_to(expected)) self.assertEqual(expectedMessage, str(e.exception)) def testAssertionErrorShouldIncludeOptionalReason(self): expected = 'EXPECTED' actual = 'ACTUAL' expectedMessage = "REASON\nExpected: 'EXPECTED'\n but: was 'ACTUAL'\n" with self.assertRaises(AssertionError) as e: assert_that(actual, equal_to(expected), 'REASON') self.assertEqual(expectedMessage, str(e.exception)) def testAssertionUnicodeEncodesProperly(self): expected = 'EXPECTED' actual = u('\xdcnic\N{Latin Small Letter O with diaeresis}de') with self.assertRaises(AssertionError): assert_that(actual, equal_to(expected), 'REASON') def testCanTestBoolDirectly(self): assert_that(True, 'should accept True') with self.assertRaises(AssertionError) as e: assert_that(False, 'FAILURE REASON') self.assertEqual('FAILURE REASON', str(e.exception)) def testCanTestBoolDirectlyWithoutReason(self): assert_that(True) with self.assertRaises(AssertionError) as e: assert_that(False) self.assertEqual('Assertion failed', str(e.exception)) if __name__ == "__main__": unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/base_description_test.py000066400000000000000000000032051266666136400256140ustar00rootroot00000000000000# coding: utf-8 import six import pytest from mock import sentinel, patch from hamcrest.core.base_description import BaseDescription from hamcrest.core.selfdescribing import SelfDescribing __author__ = "Chris Rose" __copyright__ = "Copyright 2015 hamcrest.org" __license__ = "BSD, see License.txt" class Collector(BaseDescription): def __init__(self): self.appended = [] def append(self, obj): self.appended.append(obj) class Described(SelfDescribing): def describe_to(self, desc): desc.append('described') @pytest.fixture def desc(): return Collector() def test_append_text_delegates(desc): desc.append_text(sentinel.Text) assert desc.appended == [sentinel.Text] @pytest.mark.parametrize('described, appended', ( (Described(), 'described'), pytest.mark.skipif(six.PY3, reason="py2 only")((six.u('unicode-py2'), "'unicode-py2'")), pytest.mark.skipif(six.PY3, reason="py2 only")((six.b('bytes-py2'), "'bytes-py2'")), pytest.mark.skipif(six.PY2, reason="py3 only")((six.u('unicode-py3'), "'unicode-py3'")), pytest.mark.skipif(six.PY2, reason="py3 only")((six.b('bytes-py3'), "")), (six.u("\U0001F4A9"), six.u("'{0}'").format(six.u("\U0001F4A9"))), )) def test_append_description_types(desc, described, appended): desc.append_description_of(described) assert ''.join(desc.appended) == appended @pytest.mark.parametrize("char, rep", ( ("'", r"'"), ("\n", r"\n"), ("\r", r"\r"), ("\t", r"\t"), )) def test_string_in_python_syntax(desc, char, rep): desc.append_string_in_python_syntax(char) assert ''.join(desc.appended) == "'{0}'".format(rep) PyHamcrest-1.9.0/tests/hamcrest_unit_test/base_matcher_test.py000066400000000000000000000011501266666136400247110ustar00rootroot00000000000000if __name__ == "__main__": import sys sys.path.insert(0, '..') from hamcrest.core.base_matcher import * import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class TestingBaseMatcher(BaseMatcher): def describe_to(self, description): description.append_text('SOME DESCRIPTION') class BaseMatcherTest(unittest.TestCase): def testStrFunctionShouldDescribeMatcher(self): matcher = TestingBaseMatcher() self.assertEqual('SOME DESCRIPTION', str(matcher)) if __name__ == "__main__": unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/000077500000000000000000000000001266666136400230215ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/__init__.py000066400000000000000000000000001266666136400251200ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/is_empty_test.py000066400000000000000000000034061266666136400262660ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.is_empty import * from hamcrest_unit_test.matcher_test import MatcherTest from .sequencemixin import GeneratorForm, SequenceForm __author__ = "Chris Rose" __copyright__ = "Copyright 2012 hamcrest.org" __license__ = "BSD, see License.txt" class LengthHaver(object): def __init__(self, len_): self._len = len_ def __len__(self): return self._len class EmptyCollectionTest(MatcherTest): def testReturnsTrueForEmptyStandardCollections(self): matcher = empty() self.assert_matches('empty tuple', matcher, ()) self.assert_matches('empty list', matcher, []) self.assert_matches('emtpy dictionary', matcher, {}) def testReturnsTrueForEmptyCollectionLike(self): matcher = empty() self.assert_matches('empty protocol object', matcher, LengthHaver(0)) def testReturnsFalseForNonEmptyStandardCollections(self): matcher = empty() self.assert_does_not_match('non-empty tuple', matcher, (1,)) self.assert_does_not_match('non-empty list', matcher, [1]) self.assert_does_not_match('emtpy dictionary', matcher, {1:2}) def testReturnsFalseForNonEmptyCollectionLike(self): matcher = empty() self.assert_does_not_match('non-empty protocol object', matcher, LengthHaver(1)) def testHasReadableDescription(self): self.assert_description("an empty collection", empty()) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(empty(), []) def testDescribeMismatch(self): self.assert_mismatch_description("has 3 item(s)", empty(), [1,2,3]) self.assert_mismatch_description("does not support length", empty(), 1) PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/isdict_containing_test.py000066400000000000000000000035741266666136400301330ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.isdict_containing import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest from .quasidict import QuasiDictionary import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingTest(MatcherTest): def testMatchesDictionaryContainingMatchingKeyAndValue(self): dict = {'a': 1, 'b': 2} self.assert_matches('has a:1', has_entry(equal_to('a'), equal_to(1)), dict) self.assert_matches('has b:2', has_entry(equal_to('b'), equal_to(2)), dict) self.assert_does_not_match('no c:3', has_entry(equal_to('c'), equal_to(3)), dict) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): dict = {'a': 1, 'b': 2} self.assert_matches('has a:1', has_entry('a', equal_to(1)), dict) self.assert_matches('has b:2', has_entry(equal_to('b'), 2), dict) self.assert_does_not_match('no c:3', has_entry('c', 3), dict) def testMatchesAnyConformingDictionary(self): self.assert_matches('quasi-dictionary', has_entry(1, '1'), QuasiDictionary()) self.assert_does_not_match('non-dictionary', has_entry(1, '1'), object()) def testHasReadableDescription(self): self.assert_description("a dictionary containing ['a': <1>]", has_entry('a', 1)) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_entry('a', 1), {'a': 1}) def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'bad'", has_entry('a', 1), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", has_entry('a', 1), 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/isdict_containingentries_test.py000066400000000000000000000127331266666136400315220ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.collection.isdict_containingentries import * import platform from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest try: from unittest import skipIf import unittest except ImportError: import unittest2 as unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingEntriesTest(MatcherTest): def testMatcherCreationRequiresEvenNumberOfPositionalArgs(self): self.assertRaises(ValueError, has_entries, 'a', 'b', 'c') def testDoesNotMatchNonDictionary(self): self.assert_does_not_match('non-dictionary', has_entries('a', equal_to(1)), object()) def testMatchesDictLike(self): class DictLike(object): def __getitem__(self, key): return 'value: ' + str(key) def __contains__(self, key): return True self.assert_matches('matches a dictionary-like object', has_entries('a', equal_to('value: a')), DictLike()) def testMatchesUsingSingleDictionaryArgument(self): target = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('has a & b', has_entries({'a':equal_to(1), 'b':equal_to(2)}), target) self.assert_matches('has c & a', has_entries({'c':equal_to(3), 'a':equal_to(1)}), target) self.assert_does_not_match('no d:3', has_entries({'b':equal_to(2), 'd':equal_to(3)}), target) def testMatcheSingleDictionaryArgumentWithImplicitEqualTo(self): target = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('has a & b', has_entries({'a':1, 'b':2}), target) self.assert_matches('has c & a', has_entries({'c':3, 'a':1}), target) self.assert_does_not_match('no d:3', has_entries({'b':2, 'd': 3}), target) def testMatchesUsingKwargs(self): target = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('has a & b', has_entries(a=equal_to(1), b=equal_to(2)), target) self.assert_matches('has c & a', has_entries(c=equal_to(3), a=equal_to(1)), target) self.assert_does_not_match('no d:3', has_entries(b=equal_to(2), d=equal_to(3)), target) def testMatchesKwargsWithImplicitEqualTo(self): target = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('has a & b', has_entries(a=1, b=2), target) self.assert_matches('has c & a', has_entries(c=3, a=1), target) self.assert_does_not_match('no d:3', has_entries(b=2, d=3), target) def testMatchesDictionaryContainingSingleKeyWithMatchingValue(self): target = {'a': 1, 'b': 2} self.assert_matches('has a:1', has_entries('a', equal_to(1)), target) self.assert_matches('has b:2', has_entries('b', equal_to(2)), target) self.assert_does_not_match('no b:3', has_entries('b', equal_to(3)), target) self.assert_does_not_match('no c:2', has_entries('c', equal_to(2)), target) def testMatchesDictionaryContainingMultipleKeysWithMatchingValues(self): target = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('has a & b', has_entries('a', equal_to(1), 'b', equal_to(2)), target) self.assert_matches('has c & a', has_entries('c', equal_to(3), 'a', equal_to(1)), target) self.assert_does_not_match('no d:3', has_entries('b', equal_to(3), 'd', equal_to(3)), target) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): target = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('has a & b', has_entries('a', 1, 'b', 2), target) self.assert_matches('has c & a', has_entries('c', 3, 'a', 1), target) self.assert_does_not_match('no d:4', has_entries('b', 3, 'd', 4), target) def testHasReadableDescription(self): self.assert_description("a dictionary containing {'a': <1>, 'b': <2>}", has_entries('a', 1, 'b', 2)) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_entries('a', 1), {'a': 1}) def testMismatchDescriptionOfNonDictionaryShowsActualArgument(self): self.assert_mismatch_description("'bad' is not a mapping object", has_entries('a', 1), 'bad') def testMismatchDescriptionOfDictionaryWithNonMatchingValue(self): self.assert_mismatch_description("value for 'a' was <2>", has_entries('a', 1), {'a': 2}) def testDescribeMismatchOfNonDictionaryShowsActualArgument(self): self.assert_describe_mismatch("'bad' is not a mapping object", has_entries('a', 1), 'bad') def testDescribeMismatchOfDictionaryWithoutKey(self): d = {'a': 1, 'c': 3} self.assert_describe_mismatch("no 'b' key in <%s>" % (d, ), has_entries('a', 1, 'b', 2), d) def testDescribeMismatchOfDictionaryWithNonMatchingValue(self): self.assert_describe_mismatch("value for 'a' was <2>", has_entries('a', 1), {'a': 2}) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/isdict_containingkey_test.py000066400000000000000000000037441266666136400306430ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.isdict_containingkey import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest from .quasidict import QuasiDictionary import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingKeyTest(MatcherTest): def testMatchesSingletonDictionaryContainingKey(self): dict = {'a': 1} self.assert_matches('same single key', has_key(equal_to('a')), dict) def testMatchesDictionaryContainingKey(self): dict = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('Matches a', has_key(equal_to('a')), dict) self.assert_matches('Matches c', has_key(equal_to('c')), dict) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): dict = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('Matches c', has_key('c'), dict) def testDoesNotMatchEmptyDictionary(self): self.assert_does_not_match('empty', has_key('foo'), {}); def testDoesNotMatchDictionaryMissingKey(self): dict = {'a': 1, 'b': 2, 'c': 3} self.assert_does_not_match('no matching key', has_key('d'), dict) def testMatchesAnyConformingDictionary(self): self.assert_matches('quasi-dictionary', has_key(1), QuasiDictionary()) self.assert_does_not_match('non-dictionary', has_key(1), object()) def testHasReadableDescription(self): self.assert_description("a dictionary containing key 'a'", has_key('a')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_key('a'), {'a': 1}) def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'bad'", has_key('a'), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", has_key('a'), 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/isdict_containingvalue_test.py000066400000000000000000000037741266666136400311720ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.isdict_containingvalue import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest from .quasidict import QuasiDictionary import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingValueTest(MatcherTest): def testMatchesSingletonDictionaryContainingValue(self): dict = {'a': 1} self.assert_matches('same single value', has_value(equal_to(1)), dict) def testMatchesDictionaryContainingValue(self): dict = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('Matches 1', has_value(equal_to(1)), dict) self.assert_matches('Matches 3', has_value(equal_to(3)), dict) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): dict = {'a': 1, 'b': 2, 'c': 3} self.assert_matches('Matches 3', has_value(3), dict) def testDoesNotMatchEmptyDictionary(self): self.assert_does_not_match('empty', has_value(1), {}); def testDoesNotMatchDictionaryMissingValue(self): dict = {'a': 1, 'b': 2, 'c': 3} self.assert_does_not_match('no matching value', has_value(4), dict) def testMatchesAnyConformingDictionary(self): self.assert_matches('quasi-dictionary', has_value('1'), QuasiDictionary()) self.assert_does_not_match('non-dictionary', has_value('1'), object()) def testHasReadableDescription(self): self.assert_description("a dictionary containing value 'a'", has_value('a')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_value(1), {'a': 1}) def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'bad'", has_value(1), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", has_value(1), 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/isin_test.py000066400000000000000000000027051266666136400254000ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.isin import * from hamcrest_unit_test.matcher_test import MatcherTest from .sequencemixin import GeneratorForm, SequenceForm import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" sequence = ('a', 'b', 'c') class IsInTestBase(object): def testReturnsTrueIfArgumentIsInSequence(self): matcher = is_in(self._sequence(*sequence)) self.assert_matches('has a', matcher, 'a') self.assert_matches('has b', matcher, 'b') self.assert_matches('has c', matcher, 'c') self.assert_does_not_match('no d', matcher, 'd') def testHasReadableDescription(self): self.assert_description("one of ('a', 'b', 'c')", is_in(self._sequence(*sequence))) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(is_in(self._sequence(*sequence)), 'a') def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'bad'", is_in(self._sequence(*sequence)), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", is_in(self._sequence(*sequence)), 'bad') class IsInConcreteSequenceTest(MatcherTest, IsInTestBase, SequenceForm): pass class IsInGeneratorTest(MatcherTest, IsInTestBase, GeneratorForm): pass if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/issequence_containing_test.py000066400000000000000000000107301266666136400310100ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.issequence_containing import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest from .quasisequence import QuasiSequence from .sequencemixin import GeneratorForm, SequenceForm import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsSequenceContainingTestBase(object): def testMatchesASequenceThatContainsAnElementMatchingTheGivenMatcher(self): self.assert_matches("sequence contains 'a'", has_item(equal_to('a')), self._sequence('a', 'b', 'c')) def testNoMatchIfSequenceDoesntContainAnElementMatchingTheGivenMatcher(self): self.assert_does_not_match("sequence without 'a'", has_item(equal_to('a')), self._sequence('b', 'c')) self.assert_does_not_match('empty', has_item(equal_to('a')), []) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches("sequence contains 'a'", has_item('a'), self._sequence('a', 'b', 'c')) self.assert_does_not_match("sequence without 'a'", has_item('a'), self._sequence('b', 'c')) def testMatchesAnyConformingSequence(self): self.assert_matches('quasi-sequence', has_item(1), QuasiSequence()) self.assert_does_not_match('non-sequence', has_item(1), object()) def testHasAReadableDescription(self): self.assert_description("a sequence containing 'a'", has_item('a')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_item('a'), self._sequence('a', 'b')) def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was <42>", has_item('a'), 42) def testDescribeMismatch(self): self.assert_describe_mismatch("was <42>", has_item('a'), 42) class IsConcreteSequenceContaining(MatcherTest, SequenceForm, IsSequenceContainingTestBase): pass class IsGeneratorContaining(MatcherTest, GeneratorForm, IsSequenceContainingTestBase): pass class IsSequenceContainingItemsTestBase(object): def testShouldMatchCollectionContainingAllItems(self): self.assert_matches('contains all items', has_items(equal_to('a'), equal_to('b'), equal_to('c')), self._sequence('a', 'b', 'c')) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches('Values automatically wrapped with equal_to', has_items('a', 'b', 'c'), self._sequence('a', 'b', 'c')) def testShouldMatchCollectionContainingAllItemsInDifferentOrder(self): self.assert_matches('all items in different order', has_items('a', 'b', 'c'), self._sequence('c', 'b', 'a')) def testShouldMatchCollectionContainingAllItemsPlusExtras(self): self.assert_matches('all items plus extras', has_items('a', 'b', 'c'), self._sequence('e', 'c', 'b', 'a', 'd')) def testNoMatchIfCollectionDoesntSatisfyAllMatchers(self): self.assert_does_not_match("missing 'a'", has_items('a', 'b', 'c'), self._sequence('e', 'c', 'b', 'd')) def testHasAReadableDescription(self): self.assert_description( "(a sequence containing 'a' and a sequence containing 'b')", has_items('a', 'b')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_items('a', 'b'), self._sequence('a', 'b')) def testMismatchDescriptionShowsFirstUnmetMatcherAndActualArgument(self): self.assert_mismatch_description("a sequence containing 'a' was <42>", has_items('a', 'b'), 42) def testDescribeMismatch(self): self.assert_describe_mismatch("a sequence containing 'a' was <42>", has_items('a', 'b'), 42) class IsConcreteSequenceContainingItemsTest(MatcherTest, IsSequenceContainingItemsTestBase, SequenceForm): pass class IsGeneratorSequenceContainingItemsTest(MatcherTest, IsSequenceContainingItemsTestBase, GeneratorForm): pass if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/issequence_containinginanyorder_test.py000066400000000000000000000071241266666136400331060ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.issequence_containinginanyorder import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest from .quasisequence import QuasiSequence from .sequencemixin import SequenceForm, GeneratorForm import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsSequenceContainingInAnyOrderBase(object): def testMatchingSingleItemSequence(self): self.assert_matches("Single item sequence", contains_inanyorder(equal_to(1)), self._sequence(1)) def testMatchesSequenceInOrder(self): self.assert_matches("In order", contains_inanyorder(equal_to(1), equal_to(2)), self._sequence(1,2)) def testMatchesSequenceOutOfOrder(self): self.assert_matches("Out of order", contains_inanyorder(equal_to(1), equal_to(2)), self._sequence(2,1)) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches("Values automatically wrapped with equal_to", contains_inanyorder(1,2), self._sequence(2,1)) def testDoesNotMatchEmptySequence(self): self.assert_mismatch_description("no item matches: <1>, <2> in []", contains_inanyorder(1, 2), self._sequence()) def testEmptySequenceMatchesEmptySequence(self): self.assert_matches("Empty sequence", contains_inanyorder(), self._sequence()) def testDoesNotMatchIfOneOfMultipleItemsMismatch(self): self.assert_mismatch_description("not matched: <4>", contains_inanyorder(1,2,3), self._sequence(1,2,4)) def testDoesNotMatchWithMoreElementsThanExpected(self): self.assert_mismatch_description("not matched: <2>", contains_inanyorder(1,3), self._sequence(1,2,3)) def testDoesNotMatchWithFewerElementsThanExpected(self): self.assert_mismatch_description( "no item matches: <4> in [<1>, <2>, <3>]", contains_inanyorder(1,2,3,4), self._sequence(1,2,3)) def testMatchesAnyConformingSequence(self): self.assert_matches('quasi-sequence', contains_inanyorder(1,2), QuasiSequence()) self.assert_does_not_match('non-sequence', contains_inanyorder(1,2), object()) def testHasAReadableDescription(self): self.assert_description("a sequence over [<1>, <2>] in any order", contains_inanyorder(1,2)) def testDescribeMismatch(self): self.assert_describe_mismatch('not matched: <3>', contains_inanyorder(1,2), self._sequence(1,3)) def testDescribeMismatchOfNonSequence(self): self.assert_describe_mismatch("was <3>", contains_inanyorder(1,2), 3) def testDescribeMismatchAfterMatch(self): matcher = contains_inanyorder(1, 2, 3) matcher.matches(self._sequence(3, 1)) self.assert_describe_mismatch('no item matches: <2> in [<3>, <1>]', matcher, self._sequence(3, 1)) class IsConcreteSequenceContainingInAnyOrderTest(MatcherTest, IsSequenceContainingInAnyOrderBase, SequenceForm): pass class IsGeneratorSequenceContainingInAnyOrderTest(MatcherTest, IsSequenceContainingInAnyOrderBase, GeneratorForm): pass if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/issequence_containinginorder_test.py000066400000000000000000000056611266666136400324020ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.issequence_containinginorder import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest from .quasisequence import QuasiSequence from .sequencemixin import SequenceForm, GeneratorForm import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsSequenceContainingInOrderTestBase(object): def testMatchingSingleItemSequence(self): self.assert_matches("Single item sequence", contains(equal_to(1)), self._sequence(1)) def testMatchingMultipleItemSequence(self): self.assert_matches("Multiple item sequence", contains(equal_to(1), equal_to(2), equal_to(3)), self._sequence(1,2,3)) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches("Values automatically wrapped with equal_to", contains(1, 2, 3), self._sequence(1,2,3)) def testDoesNotMatchWithMoreElementsThanExpected(self): self.assert_mismatch_description("Not matched: <4>", contains(1,2,3), self._sequence(1,2,3,4)) def testDoesNotMatchWithFewerElementsThanExpected(self): self.assert_mismatch_description("No item matched: <3>", contains(1,2,3), self._sequence(1,2)) def testDoesNotMatchIfSingleItemMismatches(self): self.assert_mismatch_description("item 0: was <3>", contains(4), self._sequence(3)) def testDoesNotMatchIfOneOfMultipleItemsMismatch(self): self.assert_mismatch_description("item 2: was <4>", contains(1,2,3), self._sequence(1,2,4)) def testDoesNotMatchEmptySequence(self): self.assert_mismatch_description("No item matched: <4>", contains(4), self._sequence()) def testEmptySequenceMatchesEmptySequence(self): self.assert_matches("Empty sequence", contains(), self._sequence()) def testMatchesAnyConformingSequence(self): self.assert_matches('quasi-sequence', contains(1,2), QuasiSequence()) self.assert_does_not_match('non-sequence', contains(1,2), object()) def testHasAReadableDescription(self): self.assert_description("a sequence containing [<1>, <2>]", contains(1,2)) def testDescribeMismatch(self): self.assert_describe_mismatch('item 1: was <3>', contains(1,2), self._sequence(1,3)) def testDescribeMismatchOfNonSequence(self): self.assert_describe_mismatch("was <3>", contains(1,2), 3) class IsConcreteSequenceContainingInOrderTest(MatcherTest, IsSequenceContainingInOrderTestBase, SequenceForm): pass class IsGeneratorSequenceContainingInOrderTest(MatcherTest, IsSequenceContainingInOrderTestBase, GeneratorForm): pass if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/issequence_onlycontaining_test.py000066400000000000000000000054721266666136400317210ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.library.collection.issequence_onlycontaining import * from hamcrest.core.core.isequal import equal_to from hamcrest.library.number.ordering_comparison import less_than from hamcrest_unit_test.matcher_test import MatcherTest from .quasisequence import QuasiSequence from .sequencemixin import SequenceForm, GeneratorForm import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsSequenceOnlyContainingTestBase(object): def testMatchesSingletonList(self): self.assert_matches('singleton list', only_contains(equal_to(1)), self._sequence(1)) def testMatchesAllItemsWithOneMatcher(self): self.assert_matches('one matcher', only_contains(less_than(3)), self._sequence(0, 1, 2)) def testMatchesAllItemsWithMultipleMatchers(self): self.assert_matches('multiple matchers', only_contains(less_than(3), equal_to(7)), self._sequence(0, 7, 1, 2)) def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches('Values automatically wrapped with equal_to', only_contains(less_than(3), 7), self._sequence(0, 7, 1, 2)) def testDoesNotMatchListWithMismatchingItem(self): self.assert_does_not_match('3 is not less than 3', only_contains(less_than(3)), self._sequence(1, 2, 3)) def testDoesNotMatchEmptyList(self): self.assert_does_not_match('empty', only_contains('foo'), self._sequence()) def testMatchesAnyConformingSequence(self): class ObjectWithLenOnly(object): def __len__(self): return 20 self.assert_matches('quasi-sequence', only_contains(less_than(3)), QuasiSequence()) self.assert_does_not_match('non-sequence', only_contains(1), object()) self.assert_does_not_match('non-sequence with length', only_contains(1), ObjectWithLenOnly()) def testHasAReadableDescription(self): self.assert_description('a sequence containing items matching (<1> or <2>)', only_contains(1,2)) def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", only_contains(1,2), 'bad') def testDescribeMismatchOfNonSequence(self): self.assert_describe_mismatch("was <3>", only_contains(1,2), 3) class IsConcreteSequenceOnlyContainingTest(MatcherTest, IsSequenceOnlyContainingTestBase, SequenceForm): pass class IsGeneratorSequenceOnlyContainingTest(MatcherTest, IsSequenceOnlyContainingTestBase, GeneratorForm): pass if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/quasidict.py000066400000000000000000000020331266666136400253570ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import six class QuasiDictionary(object): def items(self): return QuasiDictionaryItemIterator() def keys(self): return QuasiDictionaryKeyIterator() def values(self): return QuasiDictionaryValueIterator() class BaseQuasiDictionaryIterator(six.Iterator): def __init__(self): self.index = 1 def __iter__(self): return self def __next__(self): if self.index >= 3: raise StopIteration result = self.indexToResult() self.index += 1 return result class QuasiDictionaryItemIterator(BaseQuasiDictionaryIterator): def indexToResult(self): return (self.index, str(self.index)) class QuasiDictionaryKeyIterator(BaseQuasiDictionaryIterator): def indexToResult(self): return self.index class QuasiDictionaryValueIterator(BaseQuasiDictionaryIterator): def indexToResult(self): return str(self.index) PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/quasisequence.py000066400000000000000000000010461266666136400262470ustar00rootroot00000000000000__author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" import six class QuasiSequence(object): def __iter__(self): return QuasiSequenceIterator() def __len__(self): return 2 class QuasiSequenceIterator(six.Iterator): def __init__(self): self.index = 1 def __iter__(self): return self def __next__(self): if self.index >= 3: raise StopIteration result = self.index self.index += 1 return result PyHamcrest-1.9.0/tests/hamcrest_unit_test/collection/sequencemixin.py000066400000000000000000000003161266666136400262500ustar00rootroot00000000000000class GeneratorForm(object): def _sequence(self, *objects): for i in objects: yield i class SequenceForm(object): def _sequence(self, *objects): return list(objects) PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/000077500000000000000000000000001266666136400216165ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/__init__.py000066400000000000000000000000001266666136400237150ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/allof_test.py000066400000000000000000000064421266666136400243320ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.allof import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class AllOfTest(MatcherTest): def testMatchesIfArgumentSatisfiesBothOfTwoOtherMatchers(self): self.assert_matches('both matchers', all_of(equal_to('good'), equal_to('good')), 'good') def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches('both matchers', all_of('good', 'good'), 'good') def testNoMatchIfArgumentFailsToSatisfyEitherOfTwoOtherMatchers(self): self.assert_does_not_match('first matcher', all_of(equal_to('bad'), equal_to('good')), 'good') self.assert_does_not_match('second matcher', all_of(equal_to('good'), equal_to('bad')), 'good') self.assert_does_not_match('either matcher', all_of(equal_to('bad'), equal_to('bad')), 'good') def testMatchesIfArgumentSatisfiesAllOfManyOtherMatchers(self): self.assert_matches('all matchers', all_of(equal_to('good'), equal_to('good'), equal_to('good'), equal_to('good'), equal_to('good')), 'good') def testNoMatchIfArgumentFailsToSatisfyAllOfManyOtherMatchers(self): self.assert_does_not_match('matcher in the middle', all_of(equal_to('good'), equal_to('good'), equal_to('good'), equal_to('bad'), equal_to('good'), equal_to('good')), 'good') def testHasAReadableDescription(self): self.assert_description("('good' and 'bad' and 'ugly')", all_of(equal_to('good'), equal_to('bad'), equal_to('ugly'))) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description( all_of(equal_to('good'), equal_to('good')), 'good') def testMismatchDescriptionDescribesFirstFailingMatch(self): self.assert_mismatch_description( "'good' was 'bad'", all_of(equal_to('bad'), equal_to('good')), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch( "'good' was 'bad'", all_of(equal_to('bad'), equal_to('good')), 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/anyof_test.py000066400000000000000000000066671266666136400243620ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.anyof import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class AnyOfTest(MatcherTest): def testMatchesIfArgumentSatisfiesEitherOrBothOfTwoOtherMatchers(self): self.assert_matches('first matcher', any_of(equal_to('good'), equal_to('bad')), 'good') self.assert_matches('second matcher', any_of(equal_to('bad'), equal_to('good')), 'good') self.assert_matches('both matchers', any_of(equal_to('good'), equal_to('good')), 'good') def testProvidesConvenientShortcutForMatchingWithEqualTo(self): self.assert_matches('first matcher', any_of('good', 'bad'), 'good') self.assert_matches('second matcher', any_of('bad', 'good'), 'good') self.assert_matches('both matchers', any_of('good', 'good'), 'good') def testNoMatchIfArgumentFailsToSatisfyEitherOfTwoOtherMatchers(self): self.assert_does_not_match('either matcher', any_of(equal_to('bad'), equal_to('bad')), 'good') def testMatchesIfArgumentSatisfiesAnyOfManyOtherMatchers(self): self.assert_matches('matcher in the middle', any_of(equal_to('bad'), equal_to('bad'), equal_to('good'), equal_to('bad'), equal_to('bad')), 'good') def testNoMatchIfArgumentFailsToSatisfyAnyOfManyOtherMatchers(self): self.assert_does_not_match('all matchers', any_of(equal_to('bad'), equal_to('bad'), equal_to('bad'), equal_to('bad'), equal_to('bad')), 'good') def testHasAReadableDescription(self): self.assert_description("('good' or 'bad' or 'ugly')", any_of(equal_to('good'), equal_to('bad'), equal_to('ugly'))) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description( any_of(equal_to('good'), equal_to('bad')), 'good') def testMismatchDescriptionDescribesFirstFailingMatch(self): self.assert_mismatch_description( "was 'ugly'", any_of(equal_to('bad'), equal_to('good')), 'ugly') def testDescribeMismatch(self): self.assert_describe_mismatch( "was 'ugly'", any_of(equal_to('bad'), equal_to('good')), 'ugly') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/described_as_test.py000066400000000000000000000036671266666136400256520ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.core.core.described_as import * from hamcrest.core.core.isanything import anything from hamcrest_unit_test.matcher_test import MatcherTest from .nevermatch import NeverMatch import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class DescribedAsTest(MatcherTest): def testOverridesDescriptionOfNestedMatcherWithConstructorArgument(self): m1 = described_as('m1 description', anything()) m2 = described_as('m2 description', NeverMatch()) self.assert_description('m1 description', m1) self.assert_description('m2 description', m2) def testAppendsValuesToDescription(self): m = described_as('value 1 = %0, value 2 = %1', anything(), 33, 97) self.assert_description('value 1 = <33>, value 2 = <97>', m) def testDelegatesMatchingToNestedMatcher(self): m1 = described_as('irrelevant', anything()) m2 = described_as('irrelevant', NeverMatch()) self.assertTrue(m1.matches(object())) self.assertTrue(not m2.matches('hi')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description( described_as('irrelevant', anything()), object()) def testDelegatesMismatchDescriptionToNestedMatcher(self): self.assert_mismatch_description( NeverMatch.mismatch_description, described_as('irrelevant', NeverMatch()), 'hi') def testDelegatesDescribeMismatchToNestedMatcher(self): self.assert_describe_mismatch( NeverMatch.mismatch_description, described_as('irrelevant', NeverMatch()), 'hi') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/is_test.py000066400000000000000000000046741266666136400236550ustar00rootroot00000000000000from __future__ import absolute_import from hamcrest.core.core.is_ import * import six import pytest from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import * from .nevermatch import NeverMatch __author__ = "Chris Rose" __copyright__ = "Copyright 2015 hamcrest.org" __license__ = "BSD, see License.txt" class OldClass: pass @pytest.mark.parametrize('arg, identity', ( (True, True), (False, False), )) def test_delegates_matching_to_nested_matcher(arg, identity): assert_matches(is_(equal_to(identity)), arg, "should match") @pytest.mark.parametrize('arg, identity', ( (True, False), (False, True), )) def test_delegates_mismatching_to_nested_matcher(arg, identity): assert_does_not_match(is_(equal_to(identity)), arg, "should match") def test_description_should_pass_through_matcher(): assert_description('', is_(equal_to(True))) equal_matches = pytest.mark.parametrize('arg, identity, desc', ( ('A', 'A', "'A'"), (5 + 3, 8, "<8>"), pytest.mark.issue56((tuple(), (), "<()>")), )) equal_mismatches = pytest.mark.parametrize('arg, identity, desc', ( ('B', 'A', "'A'"), (5 + 4, 8, "<8>"), )) @equal_matches def test_provides_convenient_shortcut_for_is_equal_to(arg, identity, desc): assert_matches(is_(identity), arg, 'should match') @equal_mismatches def test_provides_convenient_shortcut_for_is_equal_to_false(arg, identity, desc): assert_does_not_match(is_(identity), arg, 'should not match') @equal_matches def test_description_uses_equal_to(arg, identity, desc): assert_description(desc, is_(identity)) @pytest.mark.parametrize('arg, identity', ( ('A', str), (1, int), only_py2((OldClass(), OldClass)), )) def test_provides_instanceof_shortcut(arg, identity): assert_matches(is_(identity), arg, "should match") def test_successful_match_does_not_generate_mismatch_description(): assert_no_mismatch_description(is_('A'), 'A') def test_delegates_mismatch_description_to_nested_matcher(): assert_mismatch_description( NeverMatch.mismatch_description, is_(NeverMatch()), 'hi') def test_delegates_describe_mismatch_to_nested_matcher(): assert_describe_mismatch( NeverMatch.mismatch_description, is_(NeverMatch()), 'hi') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/isanything_test.py000066400000000000000000000017721266666136400254130ustar00rootroot00000000000000if __name__ == "__main__": import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.isanything import * from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsAnythingTest(MatcherTest): def testAlwaysEvaluatesToTrue(self): self.assert_matches('None', anything(), None) self.assert_matches('object', anything(), object()) self.assert_matches('string', anything(), 'hi') def testHasUsefulDefaultDescription(self): self.assert_description('ANYTHING', anything()) def testCanOverrideDescription(self): description = 'DESCRIPTION' self.assert_description(description, anything(description)) def testMatchAlwaysSucceedsSoShouldNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(anything(), 'hi') if __name__ == "__main__": unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/isequal_test.py000066400000000000000000000054101266666136400246720ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.isequal import * from hamcrest_unit_test.matcher_test import MatcherTest import unittest import pytest import six __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsEqualTest(MatcherTest): def testComparesObjectsUsingEquality(self): self.assert_matches('equal numbers', equal_to(1), 1) self.assert_does_not_match('unequal numbers', equal_to(1), 2) def testCanCompareNoneValues(self): self.assert_matches('None equals None', equal_to(None), None) self.assert_does_not_match('None as argument', equal_to('hi'), None) self.assert_does_not_match('None in equal_to', equal_to(None), 'hi') def testHonorsArgumentEqImplementationEvenWithNone(self): class AlwaysEqual: def __eq__(self, obj): return True class NeverEqual: def __eq__(self, obj): return False self.assert_matches("always equal", equal_to(None), AlwaysEqual()) self.assert_does_not_match("never equal", equal_to(None), NeverEqual()) def testIncludesTheResultOfCallingToStringOnItsArgumentInTheDescription(self): argument_description = 'ARGUMENT DESCRIPTION' class Argument: def __str__(self): return argument_description self.assert_description('', equal_to(Argument())) def testReturnsAnObviousDescriptionIfCreatedWithANestedMatcherByMistake(self): inner_matcher = equal_to('NestedMatcher') self.assert_description("<'NestedMatcher'>", equal_to(inner_matcher)) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(equal_to('hi'), 'hi') def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'bad'", equal_to('good'), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", equal_to('good'), 'bad') def testEqualToWithEqualBytes(self): self.assert_matches("equal for b", equal_to(six.b('a')), six.b('a')) def testNotEqualToWithEqualBytes(self): self.assert_does_not_match("equal for b", equal_to(six.b('a')), six.b('b')) @pytest.mark.skipif(six.PY2, reason="Py3 formatting") def testByteInequalityDescriptionPy3(self): self.assert_mismatch_description("was <{0!r}>".format(six.b('b')), equal_to(six.b('a')), six.b('b')) @pytest.mark.skipif(six.PY3, reason="Py2 formatting") def testByteInequalityDescriptionPy2(self): self.assert_mismatch_description("was {0!r}".format(six.b('b')), equal_to(six.b('a')), six.b('b')) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/isinstanceof_test.py000066400000000000000000000033661266666136400257240ustar00rootroot00000000000000import sys import pytest if __name__ == '__main__': sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.isinstanceof import * from hamcrest_unit_test.matcher_test import * __author__ = "Chris Rose" __copyright__ = "Copyright 2015 hamcrest.org" __license__ = "BSD, see License.txt" class Parent: pass class Child(Parent): pass @pytest.mark.parametrize('arg, matcher', ( (1, instance_of(int)), (1, instance_of((str, int))), ('foo', instance_of((str, int))), (1, instance_of((int, str))), ('foo', instance_of((int, str))), only_py2((Parent(), instance_of(Parent))), )) def test_matching_evaluation(arg, matcher): assert_matches(matcher, arg, 'same class') @pytest.mark.parametrize('arg, matcher', ( ('hi', instance_of(int)), (None, instance_of(int)), only_py2(('not a parent', instance_of(Parent))), only_py2((None, instance_of(Parent))), )) def test_mismatching_evaluation(arg, matcher): assert_does_not_match(matcher, arg, 'mismatched') @pytest.mark.parametrize('obj', ( pytest.mark.issue56(()), 'str', )) def test_matcher_creation_requires_type(obj): with pytest.raises(TypeError): instance_of(obj) @pytest.mark.parametrize('desc, type', ( ('an instance of int', int), ('an instance of Parent', Parent) )) def test_has_a_readable_description(desc, type): assert_description(desc, instance_of(type)); def test_successful_match_does_not_generate_mismatch_description(): assert_no_mismatch_description(instance_of(int), 3) def test_mismatch_description_shows_actual_argument(): assert_mismatch_description("was 'bad'", instance_of(int), 'bad') def test_describe_mismatch(): assert_describe_mismatch("was 'bad'", instance_of(int), 'bad') PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/isnone_test.py000066400000000000000000000034331266666136400245250ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.isnone import * from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsNoneTest(MatcherTest): def testEvaluatesToTrueIfArgumentIsNone(self): self.assert_matches('None', none(), None) def testEvaluatesToFalseIfArgumentIsNotNone(self): self.assert_does_not_match('not None', none(), object()) def testHasAReadableDescription(self): self.assert_description('None', none()); def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(none(), None) def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'bad'", none(), 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", none(), 'bad') class NotNoneTest(MatcherTest): def testEvaluatesToTrueIfArgumentIsNotNone(self): self.assert_matches('not None', not_none(), object()) def testEvaluatesToFalseIfArgumentIsNone(self): self.assert_does_not_match('None', not_none(), None) def testHasAReadableDescription(self): self.assert_description('not None', not_none()); def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(not_none(), 'hi') def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was ", not_none(), None) def testDescribeMismatch(self): self.assert_describe_mismatch("was ", not_none(), None) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/isnot_test.py000066400000000000000000000027771266666136400244000ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.isnot import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsNotTest(MatcherTest): def testEvaluatesToTheTheLogicalNegationOfAnotherMatcher(self): self.assert_matches('invert mismatch', is_not(equal_to('A')), 'B') self.assert_does_not_match('invert match', is_not(equal_to('A')), 'A') def testProvidesConvenientShortcutForNotEqualTo(self): self.assert_matches('invert mismatch', is_not('A'), 'B'); self.assert_does_not_match('invert match', is_not('A'), 'A'); def testProvidesConvenientShortcutForNotInstanceOf(self): self.assert_matches('invert mismatch', is_not(str), 1); self.assert_does_not_match('invert match', is_not(str), 'A'); def testHasAReadableDescription(self): self.assert_description("not 'A'", is_not('A')); def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(is_not('A'), 'B') def testMismatchDescriptionShowsActualArgument(self): self.assert_mismatch_description("was 'A'", is_not('A'), 'A') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'A'", is_not('A'), 'A') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/issame_test.py000066400000000000000000000045101266666136400245100ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.issame import * from hamcrest.core.string_description import StringDescription from hamcrest_unit_test.matcher_test import MatcherTest import re import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" ADDRESS_FORMAT = r"-?0x[0-9a-fA-F]+L?" class IsSameTest(MatcherTest): def testEvaluatesToTrueIfArgumentIsReferenceToASpecifiedObject(self): o1 = object() o2 = object() self.assert_matches('same', same_instance(o1), o1) self.assert_does_not_match('different', same_instance(o1), o2) def testDescriptionIncludesMemoryAddress(self): description = StringDescription() expected = re.compile("same instance as " + ADDRESS_FORMAT + " 'abc'") description.append_description_of(same_instance('abc')); self.assertTrue(expected.match(str(description))) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): o1 = object() self.assert_no_mismatch_description(same_instance(o1), o1) def testMismatchDescriptionShowsActualArgumentAddress(self): matcher = same_instance('foo') description = StringDescription() expected = re.compile("was " + ADDRESS_FORMAT + " 'hi'") result = matcher.matches('hi', description) self.assertFalse(result, 'Precondition: Matcher should not match item') self.assertTrue(expected.match(str(description))) def testMismatchDescriptionWithNilShouldNotIncludeAddress(self): self.assert_mismatch_description("was ", same_instance('foo'), None) def testDescribeMismatch(self): matcher = same_instance('foo') description = StringDescription() expected = re.compile("was " + ADDRESS_FORMAT + " 'hi'") matcher.describe_mismatch('hi', description) expected = re.compile("was " + ADDRESS_FORMAT + " 'hi'") self.assertTrue(expected.match(str(description)), "Expected %s to match %s" % (str(matcher), str(description))) def testDescribeMismatchWithNilShouldNotIncludeAddress(self): self.assert_describe_mismatch("was ", same_instance('foo'), None) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/nevermatch.py000066400000000000000000000010371266666136400243250ustar00rootroot00000000000000from hamcrest.core.base_matcher import BaseMatcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class NeverMatch(BaseMatcher): mismatch_description = 'NEVERMATCH' def matches(self, item, mismatch_description=None): if mismatch_description: self.describe_mismatch(item, mismatch_description) return False def describe_mismatch(self, item, mismatch_description): mismatch_description.append_text(NeverMatch.mismatch_description) PyHamcrest-1.9.0/tests/hamcrest_unit_test/core/raises_test.py000066400000000000000000000066421266666136400245250ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.core.core.raises import * from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Per Fagrell" __copyright__ = "Copyright 2013 hamcrest.org" __license__ = "BSD, see License.txt" def no_exception(*args, **kwargs): return def raise_exception(*args, **kwargs): raise AssertionError(str(args) + str(kwargs)) class RaisesTest(MatcherTest): def testMatchesIfFunctionRaisesTheExactExceptionExpected(self): self.assert_matches('Right exception', raises(AssertionError), calling(raise_exception)) def testDoesNotMatchTypeErrorIfActualIsNotCallable(self): self.assert_does_not_match('Not callable', raises(TypeError), 23) def testMatchesIfFunctionRaisesASubclassOfTheExpectedException(self): self.assert_matches('Subclassed Exception', raises(Exception), calling(raise_exception)) def testDoesNotMatchIfFunctionDoesNotRaiseException(self): self.assert_does_not_match('No exception', raises(ValueError), calling(no_exception)) def testDoesNotMatchExceptionIfRegularExpressionDoesNotMatch(self): self.assert_does_not_match('Bad regex', raises(AssertionError, "Phrase not found"), calling(raise_exception)) def testMatchesRegularExpressionToStringifiedException(self): self.assert_matches('Regex', raises(AssertionError, "(3, 1, 4)"), calling(raise_exception).with_args(3,1,4)) self.assert_matches('Regex', raises(AssertionError, "([\d, ]+)"), calling(raise_exception).with_args(3,1,4)) def testDescribeMismatchWillCallItemIfNotTheOriginalMatch(self): function = Callable() matcher = raises(AssertionError) matcher.describe_mismatch(function, object()) self.assertTrue(function.called) class CallingTest(unittest.TestCase): def testCallingDoesNotImmediatelyExecuteFunction(self): try: calling(raise_exception) except AssertionError: self.fail() else: pass def testCallingObjectCallsProvidedFunction(self): method = Callable() calling(method)() self.assertTrue(method.called) def testCallingWithFunctionReturnsObject(self): method = Callable() callable = calling(method) returned = callable.with_args(3, 1, 4, keyword1="arg1") self.assertEqual(returned, callable) def testCallingWithFunctionSetsArgumentList(self): method = Callable() calling(method).with_args(3, 1, 4, keyword1="arg1")() self.assertEqual(method.args, (3, 1, 4)) self.assertEqual(method.kwargs, {"keyword1": "arg1"}) def testCallingReturnsFunctionResult(self): returned = calling(sum).with_args((3, 1, 4))() self.assertEqual(returned, 8) class Callable(object): def __init__(self): self.called = False def __call__(self, *args, **kwargs): self.called = True self.args = args self.kwargs = kwargs PyHamcrest-1.9.0/tests/hamcrest_unit_test/integration/000077500000000000000000000000001266666136400232115ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/integration/__init__.py000066400000000000000000000000001266666136400253100ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/integration/match_equality_test.py000066400000000000000000000022011266666136400276260ustar00rootroot00000000000000if __name__ == "__main__": import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.integration.match_equality import * from hamcrest.core.core.isequal import equal_to from hamcrest.core.string_description import tostring import unittest __author__ = "Chris Rose" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class MatchEqualityWrapperTest(unittest.TestCase): def testMatcherIsEqualWhenMatchesIsTrue(self): matcher = equal_to('bar') assert match_equality(matcher) == 'bar' def testMatcherIsNotEqualWhenMatchesIsFalse(self): matcher = equal_to('bar') assert match_equality(matcher) != 'foo' def testMatcherStringIsMatcherDescription(self): matcher = equal_to('bar') assert str(match_equality(matcher)) == tostring(matcher) def testMatcherReprIsMatcher(self): matcher = equal_to('bar') assert repr(match_equality(matcher)) == tostring(matcher) def testMatchesWhenProvidedAnObject(self): assert match_equality('bar') == 'bar' if __name__ == "__main__": unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/matcher_test.py000066400000000000000000000050341266666136400237240ustar00rootroot00000000000000from hamcrest.core.string_description import StringDescription import sys import pytest try: from unittest import skipIf import unittest except ImportError: import unittest2 as unittest import logging log = logging.getLogger(__name__) __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" __tracebackhide__ = True class MatcherTest(unittest.TestCase): def assert_matches(self, message, matcher, arg): assert_matches(matcher, arg, message) def assert_does_not_match(self, message, matcher, arg): assert_does_not_match(matcher, arg, message) def assert_description(self, expected, matcher): assert_description(expected, matcher) def assert_no_mismatch_description(self, matcher, arg): assert_no_mismatch_description(matcher, arg) def assert_mismatch_description(self, expected, matcher, arg): assert_mismatch_description(expected, matcher, arg) def assert_describe_mismatch(self, expected, matcher, arg): assert_describe_mismatch(expected, matcher, arg) def assert_matches(matcher, arg, message): try: assert matcher.matches(arg), message except AssertionError: description = StringDescription() matcher.describe_mismatch(arg, description) log.error(str(description)) raise def assert_does_not_match(matcher, arg, message): assert not matcher.matches(arg), message def assert_description(expected, matcher): description = StringDescription() description.append_description_of(matcher) assert expected == str(description) def assert_no_mismatch_description(matcher, arg): description = StringDescription() result = matcher.matches(arg, description) assert result, 'Precondition: Matcher should match item' assert '' == str(description), 'Expected no mismatch description' def assert_mismatch_description(expected, matcher, arg): description = StringDescription() result = matcher.matches(arg, description) assert not result, 'Precondition: Matcher should not match item' assert expected == str(description) def assert_describe_mismatch(expected, matcher, arg): description = StringDescription() matcher.describe_mismatch(arg, description) assert expected == str(description) only_py3 = pytest.mark.skipif(sys.version_info < (3, ), reason="Only relevant in Python 3") only_py2 = pytest.mark.skipif(sys.version_info >= (3, ), reason="Only relevant in Python 2") PyHamcrest-1.9.0/tests/hamcrest_unit_test/number/000077500000000000000000000000001266666136400221565ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/number/__init__.py000066400000000000000000000000001266666136400242550ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/number/iscloseto_test.py000066400000000000000000000134561266666136400256040ustar00rootroot00000000000000import six from hamcrest.library.number.iscloseto import * from hamcrest_unit_test.matcher_test import MatcherTest try: import unittest2 as unittest except ImportError: import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsCloseToTest(MatcherTest): def testEvaluatesToTrueIfArgumentIsEqualToAValueWithinSomeError(self): matcher = close_to(1.0, 0.5) self.assert_matches('equal', matcher, 1.0) self.assert_matches('less but within delta', matcher, 0.5) self.assert_matches('greater but within delta', matcher, 1.5) self.assert_does_not_match('too small', matcher, 0.4) self.assert_does_not_match('too large', matcher, 1.6) def testMatcherCreationAcceptsOtherNumericTypes(self): for t in six.integer_types: close_to(t(5), t(1)) def testMatcherCreationRequiresNumbers(self): self.assertRaises(TypeError, close_to, 'a', 0.5) self.assertRaises(TypeError, close_to, 1.0, 'a') def testFailsIfMatchingAgainstNonNumber(self): self.assert_does_not_match('not a number', close_to(1.0, 0.5), 'a') def testHasAReadableDescription(self): self.assert_description('a numeric value within <0.5> of <1.0>', close_to(1.0, 0.5)) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(close_to(1.0, 0.5), 1.0) def testMismatchDescriptionShowsActualDeltaIfArgumentIsNumeric(self): self.assert_mismatch_description('<1.7> differed by <0.7>', close_to(1.0, 0.5), 1.7) def testMismatchDescriptionShowsActualArgumentIfNotNumeric(self): self.assert_mismatch_description("was 'bad'", close_to(1.0, 0.5), 'bad') def testDescribeMismatchShowsActualDeltaIfArgumentIsNumeric(self): self.assert_describe_mismatch('<1.7> differed by <0.7>', close_to(1.0, 0.5), 1.7) def testDescribeMismatchShowsActualArgumentIfNotNumeric(self): self.assert_describe_mismatch("was 'bad'", close_to(1.0, 0.5), 'bad') try: import numpy as np NUMPY_AVAILABLE = True except ImportError: NUMPY_AVAILABLE = False class IsNumericTest(unittest.TestCase): @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_int(self): self.assertTrue(isnumeric(np.int(1)), "Platform integer (normally either int32 or int64)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_int8(self): self.assertTrue(isnumeric(np.int8(1)), "Byte (-128 to 127)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_int16(self): self.assertTrue(isnumeric(np.int16(1)), "Integer (-32768 to 32767)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_int32(self): self.assertTrue(isnumeric(np.int32(1)), "Integer (-2147483648 to 2147483647)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_int64(self): self.assertTrue(isnumeric(np.int64(1)), "Integer (9223372036854775808 to 9223372036854775807)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_uint8(self): self.assertTrue(isnumeric(np.uint8(1)), "Unsigned integer (0 to 255)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_uint16(self): self.assertTrue(isnumeric(np.uint16(1)), "Unsigned integer (0 to 65535)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_uint32(self): self.assertTrue(isnumeric(np.uint32(1)), "Unsigned integer (0 to 4294967295)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_uint64(self): self.assertTrue(isnumeric(np.uint64(1)), "Unsigned integer (0 to 18446744073709551615)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_float(self): self.assertTrue(isnumeric(np.float(1)), "Shorthand for float64.") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_float16(self): self.assertTrue(isnumeric(np.float16(1)), "Half precision float: sign bit, 5 bits exponent, 10 bits mantissa") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_float32(self): self.assertTrue(isnumeric(np.float32(1)), "Single precision float: sign bit, 8 bits exponent, 23 bits mantissa") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_float64(self): self.assertTrue(isnumeric(np.float64(1)), "Double precision float: sign bit, 11 bits exponent, 52 bits mantissa") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_complex(self): self.assertTrue(isnumeric(np.complex(1)), "Shorthand for complex128.") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_complex64(self): self.assertTrue(isnumeric(np.complex64(1)), "Complex number, represented by two 32-bit floats (real and imaginary components)") @unittest.skipUnless(NUMPY_AVAILABLE, "Skipped because it needs NumPy") def test_numpy_numeric_type_complex128(self): self.assertTrue(isnumeric(np.complex128(1)), "Complex number, represented by two 64-bit floats (real and imaginary components)") if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/number/ordering_comparison_test.py000066400000000000000000000060761266666136400276430ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.number.ordering_comparison import * from datetime import date from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class OrderingComparisonTest(MatcherTest): def testComparesObjectsForGreaterThan(self): self.assert_matches('match', greater_than(1), 2) self.assert_does_not_match('no match', greater_than(1), 1) def testComparesObjectsForLessThan(self): self.assert_matches('match', less_than(1), 0) self.assert_does_not_match('no match', less_than(1), 1) def testComparesObjectsForGreaterThanOrEqualTo(self): self.assert_matches('match', greater_than_or_equal_to(1), 2) self.assert_matches('match', greater_than_or_equal_to(1), 1) self.assert_does_not_match('no match', greater_than_or_equal_to(1), 0) def testComparesObjectsForLessThanOrEqualTo(self): self.assert_matches('match', less_than_or_equal_to(1), 0) self.assert_matches('match', less_than_or_equal_to(1), 1) self.assert_does_not_match('no match', less_than_or_equal_to(1), 2) def testSupportsDifferentTypesOfComparableObjects(self): self.assert_matches('strings', greater_than('bb'), 'cc') self.assert_matches('dates', less_than(date.today()), date.min) def testHasAReadableDescription(self): self.assert_description('a value greater than <1>', greater_than(1)) self.assert_description('a value greater than or equal to <1>', greater_than_or_equal_to(1)) self.assert_description('a value less than <1>', less_than(1)) self.assert_description('a value less than or equal to <1>', less_than_or_equal_to(1)) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(greater_than(1), 2) self.assert_no_mismatch_description(less_than(1), 0) self.assert_no_mismatch_description(greater_than_or_equal_to(1), 1) self.assert_no_mismatch_description(less_than_or_equal_to(1), 1) def testMismatchDescription(self): self.assert_mismatch_description("was <0>", greater_than(1), 0) self.assert_mismatch_description("was <2>", less_than(1), 2) self.assert_mismatch_description("was <0>", greater_than_or_equal_to(1), 0) self.assert_mismatch_description("was <2>", less_than_or_equal_to(1), 2) def testDescribeMismatch(self): self.assert_describe_mismatch("was <0>", greater_than(1), 0) self.assert_describe_mismatch("was <2>", less_than(1), 2) self.assert_describe_mismatch("was <0>", greater_than_or_equal_to(1), 0) self.assert_describe_mismatch("was <2>", less_than_or_equal_to(1), 2) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/object/000077500000000000000000000000001266666136400221345ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/object/__init__.py000066400000000000000000000000001266666136400242330ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/object/haslength_test.py000066400000000000000000000047471266666136400255360ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.object.haslength import * from hamcrest.core.core.isequal import equal_to from hamcrest.library.number.ordering_comparison import greater_than from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class FakeWithLen(object): def __init__(self, len): self.len = len def __len__(self): return self.len def __str__(self): return 'FakeWithLen' class FakeWithoutLen(object): def __str__(self): return 'FakeWithoutLen' class HasLengthTest(MatcherTest): def testPassesResultOfLenToNestedMatcher(self): self.assert_matches('equal', has_length(equal_to(42)), FakeWithLen(42)) self.assert_does_not_match('unequal', has_length(equal_to(42)), FakeWithLen(1)) def testProvidesConvenientShortcutForHasLengthEqualTo(self): self.assert_matches('equal', has_length(42), FakeWithLen(42)) self.assert_does_not_match('unequal', has_length(42), FakeWithLen(1)) def testDoesNotMatchObjectWithoutLen(self): self.assert_does_not_match('no length', has_length(42), object()) def testHasReadableDescription(self): self.assert_description('an object with length of a value greater than <5>', has_length(greater_than(5))) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_length(3), 'foo') def testMismatchDescriptionForItemWithWrongLength(self): self.assert_mismatch_description('was with length of <4>', has_length(3), FakeWithLen(4)) def testMismatchDescriptionForItemWithoutLength(self): self.assert_mismatch_description("was ", has_length(3), FakeWithoutLen()) def testDescribeMismatchForItemWithWrongLength(self): self.assert_describe_mismatch('was with length of <4>', has_length(3), FakeWithLen(4)) def testDescribeMismatchForItemWithoutLength(self): self.assert_describe_mismatch("was ", has_length(3), FakeWithoutLen()) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/object/hasproperty_test.py000066400000000000000000000117551266666136400261360ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.object.hasproperty import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Chris Rose" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class OnePropertyOldStyle: field = 'value' field2 = 'value2' class OnePropertyNewStyle(object): field = 'value' field2 = 'value2' def __repr__(self): return 'OnePropertyNewStyle' def __str__(self): return repr(self) class OverridingOldStyle: def __getattr__(self, name): if name == 'field': return 'value' if name == 'field2': return 'value2' raise AttributeError(name) class OverridingNewStyleGetAttr(object): def __getattr__(self, name): if name == 'field': return 'value' if name == 'field2': return 'value2' raise AttributeError(name) class OverridingNewStyleGetAttribute(object): def __getattribute__(self, name): if name == 'field': return 'value' if name == 'field2': return 'value2' raise AttributeError(name) class ObjectPropertyMatcher(object): match_sets = ( ("old-style: %s", OnePropertyOldStyle), ('new-style: %s', OnePropertyNewStyle), ('old-style, overriding: %s', OverridingOldStyle), ('new-style, using getattr: %s', OverridingNewStyleGetAttr), ('new-style, using getattribute: %s', OverridingNewStyleGetAttribute), ) def assert_matches_for_all_types(self, description, matcher): for description_fmt, target_class in self.match_sets: self.assert_matches(description_fmt % description, matcher, target_class()) def assert_does_not_match_for_all_types(self, description, matcher): for description_fmt, target_class in self.match_sets: self.assert_does_not_match(description_fmt % description, matcher, target_class()) class HasPropertyTest(MatcherTest, ObjectPropertyMatcher): def testHasPropertyWithoutValueMatcher(self): self.assert_matches_for_all_types('has property with name', has_property('field')) def testHasPropertyWithoutValueMatcherNegative(self): self.assert_does_not_match_for_all_types('has property with name', has_property('not_there')) def testHasPropertyWithValueMatcher(self): self.assert_matches_for_all_types('has property with name and value', has_property('field', 'value')) def testHasPropertyWithValueMatcherNegative(self): self.assert_does_not_match_for_all_types('has property with name', has_property('field', 'not the value')) def testDescription(self): self.assert_description("an object with a property 'field' matching ANYTHING", has_property('field')) self.assert_description("an object with a property 'field' matching 'value'", has_property('field', 'value')) def testDescribeMissingProperty(self): self.assert_mismatch_description(" did not have the 'not_there' property", has_property('not_there'), OnePropertyNewStyle()) def testDescribePropertyValueMismatch(self): self.assert_mismatch_description("property 'field' was 'value'", has_property('field', 'another_value'), OnePropertyNewStyle()) def testMismatchDescription(self): self.assert_describe_mismatch(" did not have the 'not_there' property", has_property('not_there'), OnePropertyNewStyle()) def testNoMismatchDescriptionOnMatch(self): self.assert_no_mismatch_description(has_property('field', 'value'), OnePropertyNewStyle()) class HasPropertiesTest(MatcherTest, ObjectPropertyMatcher): def testMatcherCreationRequiresEvenNumberOfPositionalArguments(self): self.assertRaises(ValueError, has_properties, 'a', 'b', 'c') def testMatchesUsingSingleDictionaryArgument(self): # import pdb; pdb.set_trace() self.assert_matches_for_all_types('matches using a single-argument dictionary', has_properties({'field':'value', 'field2': 'value2'})) def testMatchesUsingKeywordArguments(self): self.assert_matches_for_all_types('matches using a kwarg dict', has_properties(field='value', field2='value2')) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/object/hasstring_test.py000066400000000000000000000033141266666136400255500ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.object.hasstring import * from hamcrest.core.core.isequal import equal_to from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class FakeWithStr(object): def __str__(self): return 'FakeWithStr' class HasStringTest(MatcherTest): def testPassesResultOfToStrToNestedMatcher(self): self.assert_matches('equal', has_string(equal_to('FakeWithStr')), FakeWithStr()) self.assert_does_not_match('unequal', has_string(equal_to('FakeWithStr')), 3) def testProvidesConvenientShortcutForHasStringEqualTo(self): self.assert_matches('equal', has_string('FakeWithStr'), FakeWithStr()) self.assert_does_not_match('unequal', has_string('FakeWithStr'), 3) def testHasReadableDescription(self): self.assert_description("an object with str 'foo'", has_string('foo')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(has_string('FakeWithStr'), FakeWithStr()) def testMismatchDescription(self): self.assert_mismatch_description("was ", has_string('foo'), FakeWithStr()) def testDescribeMismatchDescription(self): self.assert_describe_mismatch("was ", has_string('foo'), FakeWithStr()) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/string_description_test.py000066400000000000000000000043321266666136400262120ustar00rootroot00000000000000import six from hamcrest.core.string_description import * from hamcrest.core.selfdescribing import SelfDescribing import re import pytest try: import unittest2 as unittest except ImportError: import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class FakeSelfDescribing(SelfDescribing): def describe_to(self, description): description.append_text('DESCRIPTION') class StringDescriptionTest(unittest.TestCase): def setUp(self): self.description = StringDescription() def testLetsSelfDescribingObjectDescribeItself(self): self.description.append_description_of(FakeSelfDescribing()) self.assertEqual('DESCRIPTION', str(self.description)) def testDescribesStringInQuotes(self): self.description.append_description_of('FOO') self.assertEqual("'FOO'", str(self.description)) def testWrapsNonSelfDescribingObjectInAngleBrackets(self): self.description.append_description_of(42) self.assertEqual('<42>', str(self.description)) def testShouldNotAddAngleBracketsIfObjectDescriptionAlreadyHasThem(self): self.description.append_description_of(object()) expected = re.compile("") self.assertTrue(expected.match(str(self.description))) @unittest.skip("Describe unicode strings doesn't malform in Python 3. Six makes this go away anyway :/") def testDescribeUnicodeStringAsBytes(self): self.description.append_description_of(six.u('\u05d0')) self.assertEqual(six.u('\\u05d0'), str(self.description)) @unittest.skipUnless(six.PY3, "Describe unicode strings only malforms in Python 2") def testDescribeUnicodeStringAsUnicode(self): self.description.append_description_of(six.u('\u05d0')) self.assertEqual(six.u("'\u05d0'"), str(self.description)) # below is a set of things that should append without error to string # descriptions @pytest.mark.parametrize('valid_input', ('native', six.b('bytes'), six.u('unicode'))) def test_description_append_valid_input(valid_input): desc = StringDescription() desc.append(valid_input) str(desc) if __name__ == "__main__": unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/000077500000000000000000000000001266666136400216525ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/__init__.py000066400000000000000000000000001266666136400237510ustar00rootroot00000000000000PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/isequal_ignoring_case_test.py000066400000000000000000000041321266666136400276150ustar00rootroot00000000000000import six from hamcrest.library.text.isequal_ignoring_case import equal_to_ignoring_case from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" matcher = equal_to_ignoring_case('heLLo') class IsEqualIgnoringCaseTest(MatcherTest): def testIgnoresCaseOfCharsInString(self): self.assert_matches('all upper', matcher, 'HELLO') self.assert_matches('all lower', matcher, 'hello') self.assert_matches('mixed up', matcher, 'HelLo') self.assert_does_not_match('no match', matcher, 'bye') def testFailsIfAdditionalWhitespaceIsPresent(self): self.assert_does_not_match('whitespace suffix', matcher, 'heLLo ') self.assert_does_not_match('whitespace prefix', matcher, ' heLLo') def testMatcherCreationRequiresString(self): self.assertRaises(TypeError, equal_to_ignoring_case, 3) def testFailsIfMatchingAgainstNonString(self): self.assert_does_not_match('non-string', matcher, object()) def testCanApplyUnicodeStringToUnicodeMatcher(self): self.assert_matches('unicode-unicode', equal_to_ignoring_case(six.u('heLLo')), six.u('HelLo')) def testCanApplyPlainStringToUnicodeMatcher(self): self.assert_matches('unicode-ascii', equal_to_ignoring_case(six.u('heLLo')), 'HelLo') def testCanApplyUnicodeStringToPlainMatcher(self): self.assert_matches('ascii-unicode', equal_to_ignoring_case('heLLo'), six.u('HelLo')) def testHasAReadableDescription(self): self.assert_description("'heLLo' ignoring case", matcher) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(matcher, 'hello') def testMismatchDescription(self): self.assert_mismatch_description("was 'bad'", matcher, 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", matcher, 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/isequal_ignoring_whitespace_test.py000066400000000000000000000054761266666136400310520ustar00rootroot00000000000000import six from hamcrest.library.text.isequal_ignoring_whitespace import * from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" matcher = equal_to_ignoring_whitespace('Hello World how\n are we? ') class IsEqualIgnoringWhiteSpaceTest(MatcherTest): def testPassesIfWordsAreSameButWhitespaceDiffers(self): self.assert_matches('less whitespace', matcher, 'Hello World how are we?') self.assert_matches('more whitespace', matcher, ' Hello World how are \n\n\twe?') def testFailsIfTextOtherThanWhitespaceDiffers(self): self.assert_does_not_match('wrong word', matcher, 'Hello PLANET how are we?') self.assert_does_not_match('incomplete', matcher, 'Hello World how are we') def testFailsIfWhitespaceIsAddedOrRemovedInMidWord(self): self.assert_does_not_match('need whitespace between Hello and World', matcher, 'HelloWorld how are we?') self.assert_does_not_match('wrong whitespace within World', matcher, 'Hello Wo rld how are we?') def testMatcherCreationRequiresString(self): self.assertRaises(TypeError, equal_to_ignoring_whitespace, 3) def testFailsIfMatchingAgainstNonString(self): self.assert_does_not_match('non-string', matcher, object()) def testCanApplyUnicodeStringToUnicodeMatcher(self): self.assert_matches('unicode-unicode', equal_to_ignoring_whitespace(six.u('foo\nbar')), six.u('foo bar')) def testCanApplyPlainStringToUnicodeMatcher(self): self.assert_matches('unicode-ascii', equal_to_ignoring_whitespace(six.u('foo\nbar')), 'foo bar') def testCanApplyUnicodeStringToPlainMatcher(self): self.assert_matches('ascii-unicode', equal_to_ignoring_whitespace('foo\n bar'), six.u('foo bar')) def testDescribesItselfAsIgnoringWhiteSpace(self): self.assert_description("'foo\\nbar' ignoring whitespace", equal_to_ignoring_whitespace('foo\nbar')) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description( equal_to_ignoring_whitespace('foo\nbar'), 'foo bar') def testMismatchDescription(self): self.assert_mismatch_description("was 'bad'", matcher, 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", matcher, 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/stringcontains_test.py000066400000000000000000000040331266666136400263300ustar00rootroot00000000000000from __future__ import with_statement import six from hamcrest.library.text.stringcontains import contains_string from hamcrest_unit_test.matcher_test import * import unittest import pytest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" if six.PY2: matcher_args = ("EXCERPT", six.u("EXCERPT")) else: matcher_args = ("EXCERPT",) @pytest.fixture(scope="module", params=matcher_args) def matcher(request): return contains_string(request.param) TEST_MATCHING_STRINGS = ( ("EXCERPTEND",), ("STARTEXCERPTEND",), ("STARTEXCERPT",), ("EXCERPTEXCERPT",), ("EXCERPT",), ) if six.PY2: TEST_MATCHING_STRINGS += ( (six.u("EXCERPTEND"),), (six.u("STARTEXCERPTEND"),), (six.u("STARTEXCERPT"),), (six.u("EXCERPTEXCERPT"),), (six.u("EXCERPT"),), ) TEST_MISMATCHING_STRINGS = ( ("whatever",), ("EXCERP",), (object(),), ) @pytest.mark.parametrize(['text'], TEST_MATCHING_STRINGS) def test_evaluates_true_if_argument_contains_substring(text, matcher): assert_matches(matcher, text, "assert that %s matches %s" % (text, matcher)) @pytest.mark.parametrize(['text'], TEST_MISMATCHING_STRINGS) def test_evaluates_false_with_mismatch(text, matcher): assert_does_not_match(matcher, text, "%s was not in string %s" % (matcher, text)) def testMatcherCreationRequiresString(): with pytest.raises(TypeError): contains_string(3) def test_description(matcher): assert_description("a string containing 'EXCERPT'", matcher) def test_successful_match_does_not_have_mismatch_description(matcher): assert_no_mismatch_description(matcher, "EXCERPT") @pytest.mark.parametrize(['text'], TEST_MISMATCHING_STRINGS) def test_mismatch_description(matcher, text): if isinstance(text, six.string_types): check_str = "'%s'" % text else: check_str = "%s" % text assert_mismatch_description("was %s" % check_str, matcher, text) if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/stringcontainsinorder_test.py000066400000000000000000000041131266666136400277120ustar00rootroot00000000000000if __name__ == '__main__': import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.text import string_contains_in_order from hamcrest.core.string_description import StringDescription from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Romilly Cocking" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" matcher = string_contains_in_order('string one', 'string two', 'string three') class StringContainsInOrderTest(MatcherTest): def testMatchesIfOrderIsCorrect(self): self.assert_matches('correct order', matcher, 'string one then string two followed by string three') def testDoesNotMatchIfOrderIsIncorrect(self): self.assert_does_not_match('incorrect order', matcher, 'string two then string one followed by string three') def testDoesNotMatchIfExpectedSubstringsAreMissing(self): self.assert_does_not_match('missing string one', matcher, 'string two then string three') self.assert_does_not_match('missing string two', matcher, 'string one then string three') self.assert_does_not_match('missing string three', matcher, 'string one then string two') def testMatcherCreationRequiresString(self): self.assertRaises(TypeError, string_contains_in_order, 3) def testFailsIfMatchingAgainstNonString(self): self.assert_does_not_match('non-string', matcher, object()) def testHasAReadableDescription(self): self.assert_description("a string containing 'string one', 'string two', 'string three' in order", matcher) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(matcher, 'string one then string two followed by string three') def testMismatchDescription(self): self.assert_mismatch_description("was 'bad'", matcher, 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", matcher, 'bad') PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/stringendswith_test.py000066400000000000000000000046271266666136400263500ustar00rootroot00000000000000import six from hamcrest.library.text.stringendswith import * from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" EXCERPT = 'EXCERPT' matcher = ends_with(EXCERPT) class StringEndsWithTest(MatcherTest): def testEvaluatesToTrueIfArgumentContainsSpecifiedSubstring(self): self.assert_does_not_match('excerpt at beginning', matcher, EXCERPT + 'END') self.assert_matches('excerpt at end', matcher, 'START' + EXCERPT) self.assert_does_not_match('excerpt in middle', matcher, 'START' + EXCERPT + 'END') self.assert_matches('excerpt repeated', matcher, EXCERPT + EXCERPT) self.assert_does_not_match('excerpt not in string', matcher, 'whatever') self.assert_does_not_match('only part of excerpt is at end of string', matcher, EXCERPT[1:]) def testEvaluatesToTrueIfArgumentIsEqualToSubstring(self): self.assert_matches('excerpt is entire string', matcher, EXCERPT) def testMatcherCreationRequiresString(self): self.assertRaises(TypeError, ends_with, 3) def testFailsIfMatchingAgainstNonString(self): self.assert_does_not_match('non-string', matcher, object()) def testCanApplyUnicodeStringToUnicodeMatcher(self): self.assert_matches('unicode-unicode', ends_with(six.u('baz')), six.u('foo bar baz')) def testCanApplyPlainStringToUnicodeMatcher(self): self.assert_matches('unicode-ascii', ends_with(six.u('baz')), 'foo bar baz') def testCanApplyUnicodeStringToPlainMatcher(self): self.assert_matches('ascii-unicode', ends_with(six.u('baz')), six.u('foo bar baz')) def testHasAReadableDescription(self): self.assert_description("a string ending with 'EXCERPT'", matcher) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(matcher, EXCERPT) def testMismatchDescription(self): self.assert_mismatch_description("was 'bad'", matcher, 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", matcher, 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/stringmatches_test.py000066400000000000000000000043671266666136400261500ustar00rootroot00000000000000if __name__ == "__main__": import sys sys.path.insert(0, '..') sys.path.insert(0, '../..') from hamcrest.library.text.stringmatches import * from hamcrest_unit_test.matcher_test import MatcherTest import re try: import unittest2 as unittest except ImportError: import unittest __author__ = "Chris Rose" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" string_matcher = matches_regexp(r'--[a-z]+--') compiled_matcher = matches_regexp(re.compile(r'--[a-z]+--')) class StringMatchesTest(MatcherTest): def testMatchesWhenPatternIsFoundAtBeginning(self): self.assert_matches('pattern at beginning', string_matcher, "--a-----") def testMatchesWhenPatternIsFoundAtEnd(self): self.assert_matches('pattern at end', string_matcher, "-----a--") def testMatchesWhenPatternIsFoundInMiddle(self): self.assert_matches('pattern in the middle', string_matcher, "-----a-----") def testMismatchesWhenPatternIsNotPresent(self): self.assert_does_not_match('pattern nowhere', string_matcher, "--0--") def testMatchesUsingCompiledExpressions(self): self.assert_matches('pattern nowhere', compiled_matcher, "--a--") def testMismatchesUsingCompiledExpressions(self): self.assert_does_not_match('pattern nowhere', compiled_matcher, "--0--") def testStringHasAReadableDescription(self): self.assert_description("a string matching '--[a-z]+--'", string_matcher) def testPatternHasAReadableDescription(self): self.assert_description("a string matching '--[a-z]+--'", compiled_matcher) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(string_matcher, '--a--') def testStringMismatchDescription(self): self.assert_mismatch_description("was 'bad'", string_matcher, 'bad') def testCompiledMismatchDescription(self): self.assert_mismatch_description("was 'bad'", compiled_matcher, 'bad') def testStringDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", string_matcher, 'bad') def testCompiledDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", compiled_matcher, 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/hamcrest_unit_test/text/stringstartswith_test.py000066400000000000000000000047211266666136400267320ustar00rootroot00000000000000import six from hamcrest.library.text.stringstartswith import * from hamcrest.core.assert_that import assert_that from hamcrest.core.core.isnot import is_not from hamcrest_unit_test.matcher_test import MatcherTest import unittest __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" EXCERPT = 'EXCERPT' matcher = starts_with(EXCERPT) stringstartswith = starts_with(EXCERPT) class StringStartsWithTest(MatcherTest): def testEvaluatesToTrueIfArgumentContainsSpecifiedSubstring(self): self.assert_matches('excerpt at beginning', matcher, EXCERPT + 'END') self.assert_does_not_match('excerpt at end', matcher, 'START' + EXCERPT) self.assert_does_not_match('excerpt in middle', matcher, 'START' + EXCERPT + 'END') self.assert_matches('excerpt repeated', matcher, EXCERPT + EXCERPT) self.assert_does_not_match('excerpt not in string',matcher, 'whatever') self.assert_does_not_match('only part of excerpt',matcher, EXCERPT[1:]) def testEvaluatesToTrueIfArgumentIsEqualToSubstring(self): self.assert_matches('excerpt is entire string', matcher, EXCERPT) def testMatcherCreationRequiresString(self): self.assertRaises(TypeError, starts_with, 3) def testFailsIfMatchingAgainstNonString(self): self.assert_does_not_match('non-string', matcher, object()) def testCanApplyUnicodeStringToUnicodeMatcher(self): self.assert_matches('unicode-unicode', starts_with(six.u('foo')), six.u('foo bar baz')) def testCanApplyPlainStringToUnicodeMatcher(self): self.assert_matches('unicode-ascii', starts_with(six.u('foo')), 'foo bar baz') def testCanApplyUnicodeStringToPlainMatcher(self): self.assert_matches('ascii-unicode', starts_with(six.u('foo')), six.u('foo bar baz')) def testHasAReadableDescription(self): self.assert_description("a string starting with 'EXCERPT'", matcher) def testSuccessfulMatchDoesNotGenerateMismatchDescription(self): self.assert_no_mismatch_description(matcher, EXCERPT) def testMismatchDescription(self): self.assert_mismatch_description("was 'bad'", matcher, 'bad') def testDescribeMismatch(self): self.assert_describe_mismatch("was 'bad'", matcher, 'bad') if __name__ == '__main__': unittest.main() PyHamcrest-1.9.0/tests/object_import.py000066400000000000000000000003361266666136400201760ustar00rootroot00000000000000from __future__ import print_function from hamcrest import * try: class MyTest(object): pass except TypeError: print('Object class defined at {0}'.format(getattr(object, '__file__', 'NOWHERE'))) raise PyHamcrest-1.9.0/tox.ini000066400000000000000000000027321266666136400151370ustar00rootroot00000000000000[tox] envlist = py27,py32,py33,py34,pypy,docs-py3 # envlist = py26,py27,py27-numpy,py32,py33,py33-numpy,pypy # Jython is not testable, but there's no reason it should not work. # py25 and py31 are deprecated as of 1.7.2 [testenv] commands = {envbindir}/py.test [] {envpython} tests/object_import.py deps = pytest mock pytest-cov [testenv:py26] setenv = PIP_INSECURE=1 commands = {envbindir}/py.test [] deps = {[testenv]deps} unittest2 [testenv:jython] deps = pytest commands = {envbindir}/jython tests/alltests.py [] {envpython} tests/object_import.py [testenv:py27-numpy] basepython = python2.7 deps = {[testenv]deps} numpy [testenv:py32] basepython = python3.2 deps = {[testenv]deps} coverage<4.0 [testenv:py33-numpy] basepython = python3.3 deps = {[testenv]deps} numpy setenv = PYTHONHASHSEED = 4 [testenv:py34-numpy] basepython = python3.4 deps = {[testenv]deps} numpy [testenv:docs-py3] basepython = python3.4 deps = sphinx changedir = {toxinidir}/doc commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html [testenv:docs-py2] basepython = python2.7 deps = sphinx changedir = {toxinidir}/doc commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html [testenv:wheel] basepython = python3.4 deps = wheel commands = {envpython} setup.py sdist bdist_wheel upload