- cd Doc
# Sphinx is pinned so that new versions that introduce new warnings won't suddenly cause build failures.
# (Updating the version is fine as long as no warnings are raised by doing so.)
- # The theme used by the docs is stored seperately, so we need to install that as well.
- - python -m pip install sphinx~=1.6.1 blurb python-docs-theme
+ # The theme used by the docs is stored separately, so we need to install that as well.
+ - python -m pip install sphinx blurb python-docs-theme
script:
- make check suspicious html SPHINXOPTS="-q -W -j4"
- os: osx
# Check that all symbols exported by libpython start with "Py" or "_Py"
- make smelly
# `-r -w` implicitly provided through `make buildbottest`.
- - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then XVFB_RUN=xvfb-run; fi; $XVFB_RUN make buildbottest TESTOPTS="-j4 -uall,-cpu"
-
+ - |
+ if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
+ XVFB_RUN=xvfb-run;
+ fi
+ $XVFB_RUN make buildbottest TESTOPTS="-j4 -uall,-cpu"
+ if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
+ $XVFB_RUN make PYTHON=../python SPHINXOPTS="-q -W -j4" -C Doc/ venv doctest
+ fi
notifications:
email: false
webhooks:
extensions = ['sphinx.ext.coverage', 'sphinx.ext.doctest',
'pyspecific', 'c_annotations', 'escape4chm']
+
+doctest_global_setup = '''
+try:
+ import _tkinter
+except ImportError:
+ _tkinter = None
+'''
# General substitutions.
project = 'Python'
copyright = '2001-%s, Python Software Foundation' % time.strftime('%Y')
-.. _examples:
+.. _distutils_examples:
********
Examples
Example usage of some of the methods of :class:`Process`:
.. doctest::
+ :options: +ELLIPSIS
>>> import multiprocessing, time, signal
>>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
>>> print(p, p.is_alive())
- <Process(Process-1, initial)> False
+ <Process(..., initial)> False
>>> p.start()
>>> print(p, p.is_alive())
- <Process(Process-1, started)> True
+ <Process(..., started)> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print(p, p.is_alive())
- <Process(Process-1, stopped[SIGTERM])> False
+ <Process(..., stopped[SIGTERM])> False
>>> p.exitcode == -signal.SIGTERM
True
^^^^^^^^^^^^^^^^^^^
In this example, we'll use the following helper function to display match
-objects a little more gracefully:
-
-.. testcode::
+objects a little more gracefully::
def displaymatch(match):
if match is None:
"<Match: '354aa', groups=('a',)>"
To find out what card the pair consists of, one could use the
-:meth:`~Match.group` method of the match object in the following manner:
-
-.. doctest::
+:meth:`~Match.group` method of the match object in the following manner::
+ >>> pair = re.compile(r".*(.).*\1")
>>> pair.match("717ak").group(1)
'7'
creates a phonebook.
First, here is the input. Normally it may come from a file, here we are using
-triple-quoted string syntax::
+triple-quoted string syntax
+
+.. doctest::
>>> text = """Ross McFluff: 834.345.1254 155 Elm Street
...
turtle is headed.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.position()
(0.00,0.00)
>>> turtle.goto(0, 0)
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.position()
(0.00,0.00)
orientation depends on the turtle mode, see :func:`mode`.
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.setheading(22)
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.heading()
22.0
orientation depends on the turtle mode, see :func:`mode`.
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.setheading(22)
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.heading()
22.0
not change the turtle's orientation.
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.goto(0, 0)
.. doctest::
+ :skipif: _tkinter is None
>>> tp = turtle.pos()
>>> tp
unchanged.
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.goto(0, 240)
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.position()
(0.00,240.00)
Set the turtle's second coordinate to *y*, leave first coordinate unchanged.
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.goto(0, 40)
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.position()
(0.00,40.00)
=================== ====================
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.setheading(90)
>>> turtle.heading()
its start-orientation (which depends on the mode, see :func:`mode`).
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.setheading(90)
>>> turtle.goto(0, -10)
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.heading()
90.0
calculated automatically. May be used to draw regular polygons.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.position()
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.dot()
it by calling ``clearstamp(stamp_id)``.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.color("blue")
>>> turtle.stamp()
Delete stamp with given *stampid*.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.position()
(150.00,-0.00)
undo actions is determined by the size of the undobuffer.
.. doctest::
+ :skipif: _tkinter is None
>>> for i in range(4):
... turtle.fd(50); turtle.lt(80)
turtle turn instantly.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.speed()
3
Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.pos()
(440.00,-0.00)
orientation which depends on the mode - "standard"/"world" or "logo").
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
Return the turtle's x coordinate.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.left(50)
Return the turtle's y coordinate.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.left(60)
:func:`mode`).
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.left(67)
other turtle, in turtle step units.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.distance(30,40)
Default value is 360 degrees.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.left(90)
``degrees(2*math.pi)``.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.left(90)
1.5707963267948966
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.degrees(360)
thickness. If no argument is given, the current pensize is returned.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.pensize()
1
attributes in one statement.
.. doctest::
+ :skipif: _tkinter is None
:options: +NORMALIZE_WHITESPACE
>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
Return ``True`` if pen is down, ``False`` if it's up.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.penup()
>>> turtle.isdown()
newly set pencolor.
.. doctest::
+ :skipif: _tkinter is None
>>> colormode()
1.0
with the newly set fillcolor.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
with the newly set colors.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.color("red", "green")
>>> turtle.color()
~~~~~~~
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> turtle.home()
Return fillstate (``True`` if filling, ``False`` else).
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.begin_fill()
>>> if turtle.filling():
Fill the shape drawn after the last call to :func:`begin_fill`.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
variables to the default values.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.goto(0,-22)
>>> turtle.left(100)
drawing observably.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.hideturtle()
Make the turtle visible.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.showturtle()
deal with shapes see Screen method :func:`register_shape`.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.shape()
'classic'
resizemode("user") is called by :func:`shapesize` when used with arguments.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.resizemode()
'noresize'
of the shapes's outline.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.shapesize()
(1.0, 1.0, 1)
heading of the turtle are sheared.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
change the turtle's heading (direction of movement).
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.reset()
>>> turtle.shape("circle")
(direction of movement).
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.reset()
>>> turtle.shape("circle")
turtle (its direction of movement).
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.reset()
>>> turtle.shape("circle")
given matrix.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle = Turtle()
>>> turtle.shape("square")
can be used to define a new shape or components of a compound shape.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
procedural way:
.. doctest::
+ :skipif: _tkinter is None
>>> def turn(x, y):
... left(180)
``None``, existing bindings are removed.
.. doctest::
+ :skipif: _tkinter is None
>>> class MyTurtle(Turtle):
... def glow(self,x,y):
mouse-click event on that turtle.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.ondrag(turtle.goto)
Return the last recorded polygon.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.home()
>>> turtle.begin_poly()
turtle properties.
.. doctest::
+ :skipif: _tkinter is None
>>> mick = Turtle()
>>> joe = mick.clone()
return the "anonymous turtle":
.. doctest::
+ :skipif: _tkinter is None
>>> pet = getturtle()
>>> pet.fd(50)
TurtleScreen methods can then be called for that object.
.. doctest::
+ :skipif: _tkinter is None
>>> ts = turtle.getscreen()
>>> ts
``None``, the undobuffer is disabled.
.. doctest::
+ :skipif: _tkinter is None
>>> turtle.setundobuffer(42)
Return number of entries in the undobuffer.
.. doctest::
+ :skipif: _tkinter is None
>>> while undobufferentries():
... undo()
For example:
.. doctest::
+ :skipif: _tkinter is None
>>> s = Shape("compound")
>>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
3. Now add the Shape to the Screen's shapelist and use it:
.. doctest::
+ :skipif: _tkinter is None
>>> register_shape("myshape", s)
>>> shape("myshape")
``screen``.
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> screen = Screen()
Set or return background color of the TurtleScreen.
.. doctest::
+ :skipif: _tkinter is None
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
distorted.
.. doctest::
+ :skipif: _tkinter is None
>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
... left(45); fd(2) # a regular octagon
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> screen.reset()
Optional argument:
.. doctest::
+ :skipif: _tkinter is None
>>> screen.delay()
10
:func:`delay`).
.. doctest::
+ :skipif: _tkinter is None
>>> screen.tracer(8, 25)
>>> dist = 2
must have the focus. (See method :func:`listen`.)
.. doctest::
+ :skipif: _tkinter is None
>>> def f():
... fd(50)
must have focus. (See method :func:`listen`.)
.. doctest::
+ :skipif: _tkinter is None
>>> def f():
... fd(50)
named turtle:
.. doctest::
+ :skipif: _tkinter is None
>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point.
Install a timer that calls *fun* after *t* milliseconds.
.. doctest::
+ :skipif: _tkinter is None
>>> running = True
>>> def f():
============ ========================= ===================
.. doctest::
+ :skipif: _tkinter is None
>>> mode("logo") # resets turtle heading to north
>>> mode()
values of color triples have to be in the range 0..\ *cmode*.
.. doctest::
+ :skipif: _tkinter is None
>>> screen.colormode(1)
>>> turtle.pencolor(240, 160, 80)
do with a Tkinter Canvas.
.. doctest::
+ :skipif: _tkinter is None
>>> cv = screen.getcanvas()
>>> cv
Return a list of names of all currently available turtle shapes.
.. doctest::
+ :skipif: _tkinter is None
>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']
coordinates: Install the corresponding polygon shape.
.. doctest::
+ :skipif: _tkinter is None
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
Return the list of turtles on the screen.
.. doctest::
+ :skipif: _tkinter is None
>>> for turtle in screen.turtles():
... turtle.color("red")
center window vertically
.. doctest::
+ :skipif: _tkinter is None
>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>> # sets window to 200x200 pixels, in upper left of screen
Set title of turtle window to *titlestring*.
.. doctest::
+ :skipif: _tkinter is None
>>> screen.title("Welcome to the turtle zoo!")
Example:
.. doctest::
+ :skipif: _tkinter is None
>>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound")
.. doctest::
+ :skipif: _tkinter is None
:hide:
>>> for turtle in turtles():
.. _getting-started:
+
+.. testsetup::
+
+ import unittest
+ from unittest.mock import Mock, MagicMock, patch, call, sentinel
+
+ class SomeClass:
+ attribute = 'this is a doctest'
+
+ @staticmethod
+ def static_method():
+ pass
+
Using Mock
----------
In the example below we have a function ``some_function`` that instantiates ``Foo``
and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a
mock. The ``Foo`` instance is the result of calling the mock, so it is configured
-by modifying the mock :attr:`~Mock.return_value`.
+by modifying the mock :attr:`~Mock.return_value`. ::
>>> def some_function():
... instance = module.Foo()
the attribute you would like patched, plus optionally the value to patch it
with.
-``patch.object``:
+``patch.object``::
>>> original = SomeClass.attribute
>>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
>>> mock.assert_called_with('filename', 'r')
>>> assert handle == sentinel.file_handle, "incorrect file handle returned"
-The module name can be 'dotted', in the form ``package.module`` if needed:
+The module name can be 'dotted', in the form ``package.module`` if needed::
>>> @patch('package.module.ClassName.attribute', sentinel.attribute)
... def test():
...
>>> MyTest('test_something').test_something()
-You can stack up multiple patch decorators using this pattern:
+You can stack up multiple patch decorators using this pattern::
>>> class MyTest(unittest.TestCase):
... @patch('package.module.ClassName1')
mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response
We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock`
-method to directly set the return value for us:
+method to directly set the return value for us::
>>> something = Something()
>>> mock_response = Mock(spec=open)
>>> mock_backend.configure_mock(**config)
With these we monkey patch the "mock backend" in place and can make the real
-call:
+call::
>>> something.backend = mock_backend
>>> something.method()
Using :attr:`~Mock.mock_calls` we can check the chained call with a single
assert. A chained call is several calls in one line of code, so there will be
several entries in ``mock_calls``. We can use :meth:`call.call_list` to create
-this list of calls for us:
+this list of calls for us::
>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
mock out the ``date`` class in the module under test. The :attr:`side_effect`
attribute on the mock date class is then set to a lambda function that returns
a real date. When the mock date class is called a real date will be
-constructed and returned by ``side_effect``.
+constructed and returned by ``side_effect``. ::
>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...
... assert mymodule.date.today() == date(2010, 10, 8)
... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
- ...
Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the
module that *uses* it. See :ref:`where to patch <where-to-patch>`.
repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its
various forms) as a class decorator. This applies the patches to all test
methods on the class. A test method is identified by methods whose names start
-with ``test``:
+with ``test``::
>>> @patch('mymodule.SomeClass')
- ... class MyTest(TestCase):
+ ... class MyTest(unittest.TestCase):
...
... def test_one(self, MockSomeClass):
... self.assertIs(mymodule.SomeClass, MockSomeClass)
An alternative way of managing patches is to use the :ref:`start-and-stop`.
These allow you to move the patching into your ``setUp`` and ``tearDown`` methods.
+::
- >>> class MyTest(TestCase):
+ >>> class MyTest(unittest.TestCase):
... def setUp(self):
... self.patcher = patch('mymodule.foo')
... self.mock_foo = self.patcher.start()
If you use this technique you must ensure that the patching is "undone" by
calling ``stop``. This can be fiddlier than you might think, because if an
exception is raised in the setUp then tearDown is not called.
-:meth:`unittest.TestCase.addCleanup` makes this easier:
+:meth:`unittest.TestCase.addCleanup` makes this easier::
- >>> class MyTest(TestCase):
+ >>> class MyTest(unittest.TestCase):
... def setUp(self):
... patcher = patch('mymodule.foo')
... self.addCleanup(patcher.stop)
val.clear()
When we try to test that ``grob`` calls ``frob`` with the correct argument look
-what happens:
+what happens::
>>> with patch('mymodule.frob') as mock_frob:
... val = {6}
opportunity to copy the arguments and store them for later assertions. In this
example I'm using *another* mock to store the arguments so that I can use the
mock methods for doing the assertion. Again a helper function sets this up for
-me.
+me. ::
>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
Using patch as a context manager is nice, but if you do multiple patches you
can end up with nested with statements indenting further and further to the
-right:
+right::
- >>> class MyTest(TestCase):
+ >>> class MyTest(unittest.TestCase):
...
... def test_foo(self):
... with patch('mymodule.Foo') as mock_foo:
With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can
achieve the same effect without the nested indentation. A simple helper
method, ``create_patch``, puts the patch in place and returns the created mock
-for us:
+for us::
- >>> class MyTest(TestCase):
+ >>> class MyTest(unittest.TestCase):
...
... def create_patch(self, name):
... patcher = patch(name)
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
- {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}
+ {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'}
Mock subclasses and their attributes
Here's an example that mocks out the 'fooble' module.
+ >>> import sys
>>> mock = Mock()
>>> with patch.dict('sys.modules', {'fooble': mock}):
... import fooble
If ``patch`` is creating, and putting in place, your mocks then you can attach
them to a manager mock using the :meth:`~Mock.attach_mock` method. After
-attaching calls will be recorded in ``mock_calls`` of the manager.
+attaching calls will be recorded in ``mock_calls`` of the manager. ::
>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
... manager.attach_mock(MockClass2, 'MockClass2')
... MockClass1().foo()
... MockClass2().bar()
- ...
<MagicMock name='mock.MockClass1().foo()' id='...'>
<MagicMock name='mock.MockClass2().bar()' id='...'>
>>> manager.mock_calls
[call.MockClass1(),
- call.MockClass1().foo(),
- call.MockClass2(),
- call.MockClass2().bar()]
+ call.MockClass1().foo(),
+ call.MockClass2(),
+ call.MockClass2().bar()]
If many calls have been made, but you're only interested in a particular
sequence of them then an alternative is to use the
Quick Guide
-----------
+.. testsetup::
+
+ class ProductionClass:
+ def method(self, a, b, c):
+ pass
+
+ class SomeClass:
+ @staticmethod
+ def static_method(args):
+ return args
+
+ @classmethod
+ def class_method(cls, args):
+ return args
+
+
:class:`Mock` and :class:`MagicMock` objects create all attributes and
methods as you access them and store details of how they have been used. You
can configure them, to specify return values or limit what attributes are
The :func:`patch` decorator / context manager makes it easy to mock classes or
objects in a module under test. The object you specify will be replaced with a
-mock (or other object) during the test and restored when the test ends:
+mock (or other object) during the test and restored when the test ends::
>>> from unittest.mock import patch
>>> @patch('module.ClassName2')
The Mock Class
--------------
+.. testsetup::
+
+ import unittest
+ from unittest.mock import sentinel, DEFAULT, ANY
+ from unittest.mock import patch, call, Mock, MagicMock, PropertyMock
+ from unittest.mock import mock_open
:class:`Mock` is a flexible mock object intended to replace the use of stubs and
test doubles throughout your code. Mocks are callable and create attributes as
so you can specify a return value when it is fetched.
Fetching a :class:`PropertyMock` instance from an object calls the mock, with
- no args. Setting it calls the mock with the value being set.
+ no args. Setting it calls the mock with the value being set. ::
>>> class Foo:
... @property
Mocks created for you by :func:`patch` are automatically given names. To
attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
-method:
+method::
>>> thing1 = object()
>>> thing2 = object()
available for alternate use-cases.
:func:`patch` as function decorator, creating the mock for you and passing it into
-the decorated function:
+the decorated function::
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
can set the *return_value* to be anything you want.
To configure return values on methods of *instances* on the patched class
-you must do this on the :attr:`return_value`. For example:
+you must do this on the :attr:`return_value`. For example::
>>> class Class:
... def method(self):
...
If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
-return value of the created mock will have the same spec.
+return value of the created mock will have the same spec. ::
>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
The *new_callable* argument is useful where you want to use an alternative
class to the default :class:`MagicMock` for the created mock. For example, if
-you wanted a :class:`NonCallableMock` to be used:
+you wanted a :class:`NonCallableMock` to be used::
>>> thing = object()
>>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
...
TypeError: 'NonCallableMock' object is not callable
-Another use case might be to replace an object with an :class:`io.StringIO` instance:
+Another use case might be to replace an object with an :class:`io.StringIO` instance::
>>> from io import StringIO
>>> def foo():
When :func:`patch` is creating a mock for you, it is common that the first thing
you need to do is to configure the mock. Some of that configuration can be done
in the call to patch. Any arbitrary keywords you pass into the call will be
-used to set attributes on the created mock:
+used to set attributes on the created mock::
>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
also be configured. These aren't syntactically valid to pass in directly as
keyword arguments, but a dictionary with these as keys can still be expanded
-into a :func:`patch` call using ``**``:
+into a :func:`patch` call using ``**``::
>>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> patcher = patch('__main__.thing', **config)
If you want :func:`patch.multiple` to create mocks for you, then you can use
:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
-then the created mocks are passed into the decorated function by keyword.
+then the created mocks are passed into the decorated function by keyword. ::
>>> thing = object()
>>> other = object()
>>> test_function()
:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
-passed by keyword *after* any of the standard arguments created by :func:`patch`:
+passed by keyword *after* any of the standard arguments created by :func:`patch`::
>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
>>> test_function()
If :func:`patch.multiple` is used as a context manager, the value returned by the
-context manger is a dictionary where created mocks are keyed by name:
+context manger is a dictionary where created mocks are keyed by name::
>>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
... assert 'other' in repr(values['other'])
call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
If you are using :func:`patch` to create a mock for you then it will be returned by
-the call to ``patcher.start``.
+the call to ``patcher.start``. ::
>>> patcher = patch('package.module.ClassName')
>>> from package import module
A typical use case for this might be for doing multiple patches in the ``setUp``
-method of a :class:`TestCase`:
+method of a :class:`TestCase`::
- >>> class MyTest(TestCase):
+ >>> class MyTest(unittest.TestCase):
... def setUp(self):
... self.patcher1 = patch('package.module.Class1')
... self.patcher2 = patch('package.module.Class2')
If you use this technique you must ensure that the patching is "undone" by
calling ``stop``. This can be fiddlier than you might think, because if an
exception is raised in the ``setUp`` then ``tearDown`` is not called.
- :meth:`unittest.TestCase.addCleanup` makes this easier:
+ :meth:`unittest.TestCase.addCleanup` makes this easier::
- >>> class MyTest(TestCase):
+ >>> class MyTest(unittest.TestCase):
... def setUp(self):
... patcher = patch('package.module.Class')
... self.MockClass = patcher.start()
patch builtins
~~~~~~~~~~~~~~
You can patch any builtins within a module. The following example patches
-builtin :func:`ord`:
+builtin :func:`ord`::
>>> @patch('__main__.ord')
... def test(mock_ord):
:class:`unittest.TestLoader` finds test methods by default.
It is possible that you want to use a different prefix for your tests. You can
-inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
+inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
>>> patch.TEST_PREFIX = 'foo'
>>> value = 3
>>> args
(1, 2, 3)
>>> kwargs
- {'arg2': 'two', 'arg': 'one'}
+ {'arg': 'one', 'arg2': 'two'}
>>> args is kall[0]
True
>>> kwargs is kall[1]
>>> args
(4, 5, 6)
>>> kwargs
- {'arg2': 'three', 'arg': 'two'}
+ {'arg': 'two', 'arg2': 'three'}
>>> name is m.mock_calls[0][0]
True
attributes from the original are shown, even if they haven't been accessed
yet:
+.. doctest::
+ :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
+
>>> dir(Mock())
['assert_any_call',
+ 'assert_called',
+ 'assert_called_once',
'assert_called_once_with',
'assert_called_with',
'assert_has_calls',
+ 'assert_not_called',
'attach_mock',
...
>>> from urllib import request
behaviour you can switch it off by setting the module level switch
:data:`FILTER_DIR`:
+.. doctest::
+ :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
+
>>> from unittest import mock
>>> mock.FILTER_DIR = False
>>> dir(mock.Mock())
:meth:`__exit__` called).
Mocking context managers with a :class:`MagicMock` is common enough and fiddly
-enough that a helper function is useful.
+enough that a helper function is useful. ::
>>> m = mock_open()
>>> with patch('__main__.open', m):
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
-And for reading files:
+And for reading files::
>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
... with open('foo') as h:
modules that import modules that import modules) without a big performance
hit.
-Here's an example of it in use:
+Here's an example of it in use::
>>> from urllib import request
>>> patcher = patch('__main__.request', autospec=True)
You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
arguments in the constructor (one of which is *self*). Here's what happens if
-we try to call it incorrectly:
+we try to call it incorrectly::
>>> req = request.Request()
Traceback (most recent call last):
TypeError: <lambda>() takes at least 2 arguments (1 given)
The spec also applies to instantiated classes (i.e. the return value of
-specced mocks):
+specced mocks)::
>>> req = request.Request('foo')
>>> req
:class:`Request` objects are not callable, so the return value of instantiating our
mocked out :class:`request.Request` is a non-callable mock. With the spec in place
-any typos in our asserts will raise the correct error:
+any typos in our asserts will raise the correct error::
>>> req.add_header('spam', 'eggs')
<MagicMock name='request.Request().add_header()' id='...'>
A more serious problem is that it is common for instance attributes to be
created in the :meth:`__init__` method and not to exist on the class at all.
*autospec* can't know about any dynamically created attributes and restricts
-the api to visible attributes.
+the api to visible attributes. ::
>>> class Something:
... def __init__(self):
not necessarily the least annoying, way is to simply set the required
attributes on the mock after creation. Just because *autospec* doesn't allow
you to fetch attributes that don't exist on the spec it doesn't prevent you
-setting them:
+setting them::
>>> with patch('__main__.Something', autospec=True):
... thing = Something()
production class and add the defaults to the subclass without affecting the
production class. Both of these require you to use an alternative object as
the spec. Thankfully :func:`patch` supports this - you can simply pass the
-alternative object as the *autospec* argument:
+alternative object as the *autospec* argument::
>>> class Something:
... def __init__(self):
Sealing mocks
~~~~~~~~~~~~~
+
+.. testsetup::
+
+ from unittest.mock import seal
+
.. function:: seal(mock)
Seal will disable the creation of mock children by preventing getting or setting
If a mock instance is assigned to an attribute instead of being dynamically created
it won't be considered in the sealing chain. This allows one to prevent seal from
- fixing part of the mock object.
+ fixing part of the mock object. ::
>>> mock = Mock()
>>> mock.submock.attribute1 = 2
--- /dev/null
+make docstest in Doc now passes., and is enforced in CI