[Python-modules-commits] [case] 01/04: Import case_1.5.2+dfsg.orig.tar.gz
Christopher Stuart Hoskin
mans0954 at moszumanska.debian.org
Sat Feb 11 17:51:52 UTC 2017
This is an automated email from the git hooks/post-receive script.
mans0954 pushed a commit to branch master
in repository case.
commit bdea23fac772b285e1cd98b14978fa21b1ff1dd7
Author: Christopher Hoskin <christopher.hoskin at gmail.com>
Date: Sat Feb 11 15:40:53 2017 +0000
Import case_1.5.2+dfsg.orig.tar.gz
---
Changelog | 301 ++++++++++++++
LICENSE | 52 +++
MANIFEST.in | 4 +
PKG-INFO | 108 +++++
README.rst | 85 ++++
case/__init__.py | 42 ++
case/case.py | 285 ++++++++++++++
case/mock.py | 721 ++++++++++++++++++++++++++++++++++
case/pytest.py | 138 +++++++
case/skip.py | 327 +++++++++++++++
case/tests/__init__.py | 0
case/utils.py | 219 +++++++++++
docs/Makefile | 228 +++++++++++
docs/_static/.keep | 0
docs/_templates/sidebardonations.html | 10 +
docs/changelog.rst | 1 +
docs/conf.py | 23 ++
docs/images/celery_128.png | Bin 0 -> 22031 bytes
docs/images/favicon.ico | Bin 0 -> 4286 bytes
docs/includes/installation.txt | 46 +++
docs/includes/introduction.txt | 8 +
docs/index.rst | 22 ++
docs/make.bat | 272 +++++++++++++
docs/reference/case.case.rst | 12 +
docs/reference/case.mock.rst | 11 +
docs/reference/case.pytest.rst | 11 +
docs/reference/case.rst | 11 +
docs/reference/case.skip.rst | 11 +
docs/reference/case.utils.rst | 11 +
docs/reference/index.rst | 18 +
docs/templates/readme.txt | 32 ++
requirements/default.txt | 3 +
requirements/deps/mock.txt | 1 +
requirements/deps/nose.txt | 1 +
requirements/docs.txt | 2 +
requirements/pkgutils.txt | 7 +
requirements/py2.txt | 2 +
requirements/py26.txt | 1 +
requirements/pypy3.txt | 1 +
requirements/test-ci.txt | 2 +
requirements/test.txt | 1 +
setup.cfg | 17 +
setup.py | 136 +++++++
43 files changed, 3183 insertions(+)
diff --git a/Changelog b/Changelog
new file mode 100644
index 0000000..24f0297
--- /dev/null
+++ b/Changelog
@@ -0,0 +1,301 @@
+Changes
+=======
+
+1.5.2
+=====
+:release-date: 2016-10-28 03:40 p.m. PDT
+:release-by: Ask Solem
+
+- Using setup/teardown instead of setup_method/teardown_method was a bad idea.
+
+ Since it's way more common to override setup/teardown, and it's
+ likely people forget to call super in these methods, the change
+ crashed several test suites.
+
+ So on pytest the decorators are now back to augmenting
+ setup_method/teardown_method again.
+
+1.5.1
+=====
+:release-date: 2016-10-28 03:40 p.m. PDT
+:release-by: Ask Solem
+
+- 1.5.0 had a left over print statement :blush:
+
+.. _version-1.5.0:
+
+1.5.0
+=====
+:release-date: 2016-10-28 03:36 p.m. PDT
+:release-by: Ask Solem
+
+- Pytest: When decorating classes using the ``skip.*`` and ``mock.*``
+ decorators, these now augment ``cls.setup``/``cls.teardown`` instead of
+ ``cls.setup_method``/``cls.teardown_method``.
+
+ It's a bit hard to find in the pytest documentation, but pytest
+ will always call test_cls.setup and test_cls.teardown.
+
+- Pytest: Adds ``patching.object``.
+
+ This works exactly like :func:`unittest.mock.patch.object`,
+ you give it an object and an attribute name, and it will patch
+ that attribute on the object. It also supports the same arguments
+ and extra options.
+
+ Example:
+
+ .. code-block:: python
+
+ @pytest.fixture
+ def channel(patching):
+ c = Channel()
+ patching(c, 'connect')
+ return c
+
+.. _version-1.4.0:
+
+1.4.0
+=====
+:release-date: 2016-10-17 06:14 p.m. PDT
+:release-by: Ask Solem
+
+- Adds new helper: ``case.pytest.fixture_with_options``.
+
+ Example:
+
+ .. code-block:: python
+
+ @fixture_with_options()
+ def sftp(request,
+ username='test_username',
+ password='test_password'):
+ return {'username': username, 'password': password}
+
+ @sftp.options(username='foo', password='bar')
+ def test_foo(sftp):
+ assert sftp['username'] == 'foo'
+ assert sftp['password'] == 'bar'
+
+.. _version-1.3.1:
+
+1.3.1
+=====
+:release-date: 2016-07-22 06:14 p.m. PDT
+:release-by: Ask Solem
+
+- All case decorators now works with py.test classes.
+
+- Py.test: Adds new `stdouts` fixture that patches :data:`sys.stdout`,
+ and :data:`sys.stderr`.
+
+ Example:
+
+ .. code-block:: python
+
+ def test_x(stdouts):
+ print('foo')
+ assert 'foo' in stdouts.stdout.getvalue()
+ print('bar', file=sys.stderr)
+ assert 'bar' in stdouts.stderr.getvalue()
+
+- Py.test: The `patching` fixture can now mock modules.
+
+ Example:
+
+ .. code-block:: python
+
+ def test_x(patching):
+ gevent, gevent_monkey = patching.modules(
+ 'gevent',
+ 'gevent.monkey',
+ )
+ os = patching.modules('os')
+ gevent_monkey.patch_all.side_effect = RuntimeError()
+
+ with pytest.raises(RuntimeError):
+ from gevent import monkey
+ monkey.patch_all()
+
+.. _version-1.3.0:
+
+1.3.0
+=====
+:release-date: 2016-07-18 05:33 p.m. PDT
+:release-by: Ask Solem
+
+- Case is now a py.test plug-in and provides a `patching` fixture
+ as a shortcut to `monkeypatch` setting the value to a mock.
+
+ This does not have any effects for users not using py.test.
+
+ Example:
+
+ .. code-block:: python
+
+ def test_foo(patching):
+ # execv value here will be mock.MagicMock by default.
+ execv = patching('os.execv')
+
+ patching('sys.platform', 'darwin') # set concrete value
+ patching.setenv('DJANGO_SETTINGS_MODULE', 'x.settings')
+
+ # val will be of type mock.MagicMock by default
+ val = patching.setitem('path.to.dict', 'KEY')
+
+.. _version-1.2.3:
+
+1.2.3
+=====
+:release-date: 2016-06-15 03:00 p.m. PDT
+:release-by: Ask Solem
+
+- Case decorators now supports py.test.
+
+- Patcher created by create_patcher now accepts *args.
+
+.. _version-1.2.2:
+
+1.2.2
+=====
+:release-date: 2016-06-23 02:46 p.m. PDT
+:release-by: Ask Solem
+
+- ``mock.reload_modules``: Fixed compatibility with Python 3.
+
+.. _version-1.2.1:
+
+1.2.1
+=====
+:release-date: 2016-06-23 12:111 p.m. PDT
+:release-by: Ask Solem
+
+- ``mock.reload_modules`` now re-imports the module and
+ calls ``reload()`` on it.
+
+ This fixes issues with side effects not being properly reset after
+ context exits.
+
+.. _version-1.2.0:
+
+1.2.0
+=====
+:release-date: 2016-06-13 05:00 p.m. PDT
+:release-by: Ask Solem
+
+- Adds ``mock.mute`` decorator to suppress stdout with no return value.
+
+ Contributed by Tony Narlock.
+
+- Adds ``Mock.on_nth_call_do_raise(excA, excB, n)``.
+
+ This will make the mock raise excA until called n times, in which
+ it will start to raise excB.
+
+.. _version-1.1.4:
+
+1.1.4
+=====
+:release-date: 2016-05-12 03:04 p.m. PDT
+:release-by: Ask Solem
+
+- ``case.patch.*`` functions now supports using ``new`` as a positional
+ argument, for compatibility with ``mock.patch``.
+
+.. _version-1.1.3:
+
+1.1.3
+=====
+:release-date: 2016-04-19 04:41 p.m. PDT
+:release-by: Ask Solem
+
+- ``case.patch(autospec=True)`` now works.
+
+ This will use the original mock.MagicMock, not case.MagicMock.
+
+.. _version-1.1.2:
+
+1.1.2
+=====
+:release-date: 2016-04-08 11:34 p.m. PDT
+:release-by: Ask Solem
+
+- Also :func:`case.patch.multiple`, and :func:`case.patch.object`
+ now gives :class:`case.MagicMock`.
+
+.. _version-1.1.1:
+
+1.1.1
+=====
+:release-date: 2016-04-08 11:13 p.m. PDT
+:release-by: Ask Solem
+
+- :func:`case.patch` now gives :class:`case.MagicMock` (not
+ ``mock.MagicMock``).
+
+.. _version-1.1.0:
+
+1.1.0
+=====
+:release-date: 2016-04-08 10:00 p.m. PDT
+:release-by: Ask Solem
+
+- Adds new Mock methods from Python 3.6:
+
+ - ``Mock.assert_called()``
+ - ``Mock.assert_not_called()``
+ - ``Mock.assert_called_once()``
+
+- Adds ``Mock.create_patcher()``
+
+ Example:
+
+ .. code-block:: python
+
+ from case import Case, mock
+
+ patch_commands = mock.create_patcher('long_name.management.commands')
+
+ class test_FooCommand(Case):
+
+ @patch_commands('FooCommand.authenticate')
+ def test_foo(self, authenticate):
+ pass
+
+.. _version-1.0.3:
+
+1.0.3
+=====
+:release-date: 2016-04-06 04:00 p.m. PDT
+:release-by: Ask Solem
+
+- Python 2.6 compatibility.
+
+- ``mock.platform_pyimp`` no longer accepted default value.
+
+.. _version-1.0.2:
+
+1.0.2
+=====
+:release-date: 2016-04-06 03:46 p.m. PDT
+:release-by: Ask Solem
+
+- Adds docstrings
+
+.. _version-1.0.1:
+
+1.0.1
+=====
+:release-date: 2016-04-05 04:00 p.m. PDT
+:release-by: Ask Solem
+
+- Fixed issues with Python 3
+
+.. _version-1.0.0:
+
+1.0.0
+=====
+:release-date: 2016-04-05 02:00 p.m. PDT
+:release-by: Ask Solem
+
+- Initial release
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..582316a
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,52 @@
+Copyright (c) 2012-2016 Ask Solem & contributors. All rights reserved.
+
+CASE is licensed under The BSD License (3 Clause, also known as
+the new BSD license). The license is an OSI approved Open Source
+license and is GPL-compatible(1).
+
+The license text can also be found here:
+http://www.opensource.org/licenses/BSD-3-Clause
+
+License
+=======
+
+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 Ask Solem, 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 Ask Solem 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.
+
+Documentation License
+=====================
+
+The documentation portion of CASE (the rendered contents of the
+"docs" directory of a software distribution or checkout) is supplied
+under the "Creative Commons Attribution-ShareAlike 4.0
+International" (CC BY-SA 4.0) License as described by
+http://creativecommons.org/licenses/by-sa/4.0/
+
+Footnotes
+=========
+(1) A GPL-compatible license makes it possible to
+ combine CASE with other software that is released
+ under the GPL, it does not mean that we're distributing
+ CASE under the GPL license. The BSD license, unlike the GPL,
+ let you distribute a modified version without making your
+ changes open source.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..540601e
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,4 @@
+include README.rst Changelog LICENSE
+recursive-include docs *
+recursive-include extra README *.py
+recursive-include requirements *.txt
diff --git a/PKG-INFO b/PKG-INFO
new file mode 100644
index 0000000..c8a46fe
--- /dev/null
+++ b/PKG-INFO
@@ -0,0 +1,108 @@
+Metadata-Version: 1.1
+Name: case
+Version: 1.5.2
+Summary: Python unittest Utilities
+Home-page: http://github.com/celery/case
+Author: Ask Solem
+Author-email: ask at celeryproject.org
+License: BSD
+Description: =====================================================================
+ Python unittest utilities
+ =====================================================================
+
+ |build-status| |coverage| |license| |wheel| |pyversion| |pyimp|
+
+ :Version: 1.5.2
+ :Web: http://case.readthedocs.org/
+ :Download: http://pypi.python.org/pypi/case/
+ :Source: http://github.com/celery/case/
+ :Keywords: testing utilities, python, unittest, mock
+
+ About
+ =====
+
+ .. _case-installation:
+
+ Installation
+ ============
+
+ You can install case either via the Python Package Index (PyPI)
+ or from source.
+
+ To install using `pip`,::
+
+ $ pip install -U case
+
+ To install using `easy_install`,::
+
+ $ easy_install -U case
+
+ .. _case-installing-from-source:
+
+ Downloading and installing from source
+ --------------------------------------
+
+ Download the latest version of case from
+ http://pypi.python.org/pypi/case/
+
+ You can install it by doing the following,::
+
+ $ tar xvfz case-0.0.0.tar.gz
+ $ cd case-0.0.0
+ $ python setup.py build
+ # python setup.py install
+
+ The last command must be executed as a privileged user if
+ you are not currently using a virtualenv.
+
+ .. _case-installing-from-git:
+
+ Using the development version
+ -----------------------------
+
+ With pip
+ ~~~~~~~~
+
+ You can install the latest snapshot of case using the following
+ pip command::
+
+ $ pip install https://github.com/celery/case/zipball/master#egg=case
+
+ .. |build-status| image:: https://secure.travis-ci.org/celery/case.png?branch=master
+ :alt: Build status
+ :target: https://travis-ci.org/celery/case
+
+ .. |coverage| image:: https://codecov.io/github/celery/case/coverage.svg?branch=master
+ :target: https://codecov.io/github/celery/case?branch=master
+
+ .. |license| image:: https://img.shields.io/pypi/l/case.svg
+ :alt: BSD License
+ :target: https://opensource.org/licenses/BSD-3-Clause
+
+ .. |wheel| image:: https://img.shields.io/pypi/wheel/case.svg
+ :alt: Case can be installed via wheel
+ :target: http://pypi.python.org/pypi/case/
+
+ .. |pyversion| image:: https://img.shields.io/pypi/pyversions/case.svg
+ :alt: Supported Python versions.
+ :target: http://pypi.python.org/pypi/case/
+
+ .. |pyimp| image:: https://img.shields.io/pypi/implementation/case.svg
+ :alt: Support Python implementations.
+ :target: http://pypi.python.org/pypi/case/
+
+
+Keywords: test unit testing pytest unittest mock patch
+Platform: any
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: OS Independent
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..7042916
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,85 @@
+=====================================================================
+ Python unittest utilities
+=====================================================================
+
+|build-status| |coverage| |license| |wheel| |pyversion| |pyimp|
+
+:Version: 1.5.2
+:Web: http://case.readthedocs.org/
+:Download: http://pypi.python.org/pypi/case/
+:Source: http://github.com/celery/case/
+:Keywords: testing utilities, python, unittest, mock
+
+About
+=====
+
+.. _case-installation:
+
+Installation
+============
+
+You can install case either via the Python Package Index (PyPI)
+or from source.
+
+To install using `pip`,::
+
+ $ pip install -U case
+
+To install using `easy_install`,::
+
+ $ easy_install -U case
+
+.. _case-installing-from-source:
+
+Downloading and installing from source
+--------------------------------------
+
+Download the latest version of case from
+http://pypi.python.org/pypi/case/
+
+You can install it by doing the following,::
+
+ $ tar xvfz case-0.0.0.tar.gz
+ $ cd case-0.0.0
+ $ python setup.py build
+ # python setup.py install
+
+The last command must be executed as a privileged user if
+you are not currently using a virtualenv.
+
+.. _case-installing-from-git:
+
+Using the development version
+-----------------------------
+
+With pip
+~~~~~~~~
+
+You can install the latest snapshot of case using the following
+pip command::
+
+ $ pip install https://github.com/celery/case/zipball/master#egg=case
+
+.. |build-status| image:: https://secure.travis-ci.org/celery/case.png?branch=master
+ :alt: Build status
+ :target: https://travis-ci.org/celery/case
+
+.. |coverage| image:: https://codecov.io/github/celery/case/coverage.svg?branch=master
+ :target: https://codecov.io/github/celery/case?branch=master
+
+.. |license| image:: https://img.shields.io/pypi/l/case.svg
+ :alt: BSD License
+ :target: https://opensource.org/licenses/BSD-3-Clause
+
+.. |wheel| image:: https://img.shields.io/pypi/wheel/case.svg
+ :alt: Case can be installed via wheel
+ :target: http://pypi.python.org/pypi/case/
+
+.. |pyversion| image:: https://img.shields.io/pypi/pyversions/case.svg
+ :alt: Supported Python versions.
+ :target: http://pypi.python.org/pypi/case/
+
+.. |pyimp| image:: https://img.shields.io/pypi/implementation/case.svg
+ :alt: Support Python implementations.
+ :target: http://pypi.python.org/pypi/case/
+
diff --git a/case/__init__.py b/case/__init__.py
new file mode 100644
index 0000000..ce1ded4
--- /dev/null
+++ b/case/__init__.py
@@ -0,0 +1,42 @@
+"""Python unittest Utilities"""
+from __future__ import absolute_import, unicode_literals
+
+import re
+
+from collections import namedtuple
+
+from .case import Case
+from .mock import ANY, ContextMock, MagicMock, Mock, call, patch, sentinel
+
+from . import mock
+from . import skip
+
+__version__ = '1.5.2'
+__author__ = 'Ask Solem'
+__contact__ = 'ask at celeryproject.org'
+__homepage__ = 'http://github.com/celery/case'
+__docformat__ = 'restructuredtext'
+
+# -eof meta-
+
+version_info_t = namedtuple('version_info_t', (
+ 'major', 'minor', 'micro', 'releaselevel', 'serial'
+))
+
+# bumpversion can only search for {current_version}
+# so we have to parse the version here.
+_temp = re.match(
+ r'(\d+)\.(\d+).(\d+)(.+)?', __version__).groups()
+VERSION = version_info = version_info_t(
+ int(_temp[0]), int(_temp[1]), int(_temp[2]), _temp[3] or '', '')
+del(_temp)
+del(re)
+
+__all__ = [
+ b'Case',
+
+ b'ANY', b'ContextMock', b'MagicMock', b'Mock',
+ b'call', b'patch', b'sentinel',
+
+ b'mock', b'skip',
+]
diff --git a/case/case.py b/case/case.py
new file mode 100644
index 0000000..17375c7
--- /dev/null
+++ b/case/case.py
@@ -0,0 +1,285 @@
+from __future__ import absolute_import, unicode_literals
+
+import re
+import sys
+import types
+import warnings
+
+from contextlib import contextmanager
+from functools import partial
+from six import string_types, itervalues as values, iteritems as items
+
+from . import mock
+
+try:
+ import unittest # noqa
+ unittest.skip
+ from unittest.util import safe_repr, unorderable_list_difference
+except AttributeError:
+ import unittest2 as unittest # noqa
+ from unittest2.util import safe_repr, unorderable_list_difference # noqa
+
+__all__ = ['Case']
+
+
+# -- adds assertWarns from recent unittest2, not in Python 2.7.
+
+class _AssertRaisesBaseContext(object):
+
+ def __init__(self, expected, test_case, callable_obj=None,
+ expected_regex=None):
+ self.expected = expected
+ self.failureException = test_case.failureException
+ self.obj_name = None
+ if isinstance(expected_regex, string_types):
+ expected_regex = re.compile(expected_regex)
+ self.expected_regex = expected_regex
+
+
+def _is_magic_module(m):
+ # some libraries create custom module types that are lazily
+ # lodaded, e.g. Django installs some modules in sys.modules that
+ # will load _tkinter and other shit when touched.
+
+ # pyflakes refuses to accept 'noqa' for this isinstance.
+ cls, modtype = type(m), types.ModuleType
+ try:
+ variables = vars(cls)
+ except TypeError:
+ return True
+ else:
+ return (cls is not modtype and (
+ '__getattr__' in variables or
+ '__getattribute__' in variables))
+
+
+class _AssertWarnsContext(_AssertRaisesBaseContext):
+ """A context manager used to implement TestCase.assertWarns* methods."""
+
+ def __enter__(self):
+ # The __warningregistry__'s need to be in a pristine state for tests
+ # to work properly.
+ warnings.resetwarnings()
+ for v in list(values(sys.modules)):
+ # do not evaluate Django moved modules and other lazily
+ # initialized modules.
+ if v and not _is_magic_module(v):
+ # use raw __getattribute__ to protect even better from
+ # lazily loaded modules
+ try:
+ object.__getattribute__(v, '__warningregistry__')
+ except AttributeError:
+ pass
+ else:
+ object.__setattr__(v, '__warningregistry__', {})
+ self.warnings_manager = warnings.catch_warnings(record=True)
+ self.warnings = self.warnings_manager.__enter__()
+ warnings.simplefilter('always', self.expected)
+ return self
+
+ def __exit__(self, exc_type, exc_value, tb):
+ self.warnings_manager.__exit__(exc_type, exc_value, tb)
+ if exc_type is not None:
+ # let unexpected exceptions pass through
+ return
+ try:
+ exc_name = self.expected.__name__
+ except AttributeError:
+ exc_name = str(self.expected)
+ first_matching = None
+ for m in self.warnings:
+ w = m.message
+ if not isinstance(w, self.expected):
+ continue
+ if first_matching is None:
+ first_matching = w
+ if (self.expected_regex is not None and
+ not self.expected_regex.search(str(w))):
+ continue
+ # store warning for later retrieval
+ self.warning = w
+ self.filename = m.filename
+ self.lineno = m.lineno
+ return
+ # Now we simply try to choose a helpful failure message
+ if first_matching is not None:
+ raise self.failureException(
+ '%r does not match %r' % (
+ self.expected_regex.pattern, str(first_matching)))
+ if self.obj_name:
+ raise self.failureException(
+ '%s not triggered by %s' % (exc_name, self.obj_name))
+ else:
+ raise self.failureException('%s not triggered' % exc_name)
+
+
+class CaseMixin(object):
+ """Mixin class that adds the utility methods to any unittest TestCase
+ class."""
+
+ def patch(self, *path, **options):
+ """Patch object until test case returns.
+
+ Example::
+
+ from case import Case
+
+ class test_Frobulator(Case):
+
+ def setup(self):
+ frobulate = self.patch('some.where.Frobulator.frobulate')
+
+ """
+ manager = mock.patch('.'.join(path), **options)
+ patched = manager.start()
+ self.addCleanup(manager.stop)
+ return patched
+
+ def mock_modules(self, *mods):
+ """Mock modules for the duration of the test.
+
+ See :func:`case.mock.module`
+
+ """
+ modules = []
+ for mod in mods:
+ mod = mod.split('.')
+ modules.extend(reversed([
+ '.'.join(mod[:-i] if i else mod) for i in range(len(mod))
+ ]))
+ modules = sorted(set(modules))
+ return self.wrap_context(mock.module(*modules))
+
+ def mask_modules(self, *modules):
+ """Make modules for the duration of the test.
+
+ See :func:`case.mock.mask_modules`.
+
+ """
+ self.wrap_context(mock.mask_modules(*modules))
+
+ def wrap_context(self, context):
+ """Wrap context so that the context exits when the test completes."""
+ ret = context.__enter__()
+ self.addCleanup(partial(context.__exit__, None, None, None))
+ return ret
+
+ def mock_environ(self, env_name, env_value):
+ """Mock environment variable value for the duration of the test.
+
+ See :func:`case.mock.environ`.
+
+ """
+ return self.wrap_context(mock.environ(env_name, env_value))
+
+
+class Case(unittest.TestCase, CaseMixin):
+ """Test Case
+
+ Subclass of :class:`unittest.TestCase` adding convenience
+ methods.
+
+ **setup / teardown**
+
+ New :meth:`setup` and :meth:`teardown` methods can be defined
+ in addition to the core :meth:`setUp` + :meth:`tearDown`
+ methods.
+
+ Note: If you redefine the core :meth:`setUp` + :meth:`tearDown`
+ methods you must make sure ``super`` is called.
+ ``super`` is not necessary for the lowercase versions.
+
+ **Python 2.6 compatibility**
+
+ This class also implements :meth:`assertWarns`, :meth:`assertWarnsRegex`,
+ :meth:`assertDictContainsSubset`, and :meth:`assertItemsEqual`
+ which are not available in the original Python 2.6 unittest
+ implementation.
+
+ """
+ DeprecationWarning = DeprecationWarning
+ PendingDeprecationWarning = PendingDeprecationWarning
+
+ def setUp(self):
+ self.setup()
+
+ def tearDown(self):
+ self.teardown()
+
+ def setup(self):
+ pass
+
+ def teardown(self):
+ pass
+
+ def assertWarns(self, expected_warning):
+ return _AssertWarnsContext(expected_warning, self, None)
+
+ def assertWarnsRegex(self, expected_warning, expected_regex):
+ return _AssertWarnsContext(expected_warning, self,
+ None, expected_regex)
+
+ @contextmanager
+ def assertDeprecated(self):
+ with self.assertWarnsRegex(self.DeprecationWarning,
+ r'scheduled for removal'):
+ yield
+
+ @contextmanager
+ def assertPendingDeprecation(self):
+ with self.assertWarnsRegex(self.PendingDeprecationWarning,
+ r'scheduled for deprecation'):
+ yield
+
+ def assertDictContainsSubset(self, expected, actual, msg=None):
+ missing, mismatched = [], []
+
+ for key, value in items(expected):
+ if key not in actual:
+ missing.append(key)
+ elif value != actual[key]:
+ mismatched.append('%s, expected: %s, actual: %s' % (
+ safe_repr(key), safe_repr(value),
+ safe_repr(actual[key])))
+
+ if not (missing or mismatched):
+ return
+
+ standard_msg = ''
+ if missing:
+ standard_msg = 'Missing: %s' % ','.join(map(safe_repr, missing))
+
+ if mismatched:
+ if standard_msg:
+ standard_msg += '; '
+ standard_msg += 'Mismatched values: %s' % (
+ ','.join(mismatched))
+
+ self.fail(self._formatMessage(msg, standard_msg))
+
+ def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
+ missing = unexpected = None
+ try:
+ expected = sorted(expected_seq)
+ actual = sorted(actual_seq)
+ except TypeError:
+ # Unsortable items (example: set(), complex(), ...)
+ expected = list(expected_seq)
+ actual = list(actual_seq)
+ missing, unexpected = unorderable_list_difference(
+ expected, actual)
+ else:
+ return self.assertSequenceEqual(expected, actual, msg=msg)
+
+ errors = []
+ if missing:
+ errors.append(
+ 'Expected, but missing:\n %s' % (safe_repr(missing),)
+ )
+ if unexpected:
+ errors.append(
+ 'Unexpected, but present:\n %s' % (safe_repr(unexpected),)
+ )
+ if errors:
+ standardMsg = '\n'.join(errors)
+ self.fail(self._formatMessage(msg, standardMsg))
diff --git a/case/mock.py b/case/mock.py
new file mode 100644
index 0000000..4cbae88
--- /dev/null
+++ b/case/mock.py
@@ -0,0 +1,721 @@
+from __future__ import absolute_import, unicode_literals
+
+import importlib
+import inspect
+import logging
+import os
+import platform
+import sys
+import time
+import types
+
+from contextlib import contextmanager
+from functools import wraps
+from six import reraise, string_types, iteritems as items
+from six.moves import builtins
+
+from .utils import WhateverIO, decorator, get_logger_handlers, noop
+
+try:
+ from importlib import reload
+except ImportError:
+ try:
+ from imp import reload
+ except ImportError:
... 2482 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/case.git
More information about the Python-modules-commits
mailing list