<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>unittest.mock — mock object library — Python 3.7.4 documentation</title> <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script type="text/javascript" src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.7.4 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="unittest.mock — getting started" href="unittest.mock-examples.html" /> <link rel="prev" title="unittest — Unit testing framework" href="unittest.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <link rel="canonical" href="https://docs.python.org/3/library/unittest.mock.html" /> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/switchers.js"></script> <style> @media only screen { table.full-width-table { width: 100%; } } </style> </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="unittest.mock-examples.html" title="unittest.mock — getting started" accesskey="N">next</a> |</li> <li class="right" > <a href="unittest.html" title="unittest — Unit testing framework" accesskey="P">previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li> <span class="language_switcher_placeholder">en</span> <span class="version_switcher_placeholder">3.7.4</span> <a href="../index.html">Documentation </a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">Development Tools</a> »</li> <li class="right"> <div class="inline-search" style="display: none" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('.inline-search').show(0);</script> | </li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="module-unittest.mock"> <span id="unittest-mock-mock-object-library"></span><h1><a class="reference internal" href="#module-unittest.mock" title="unittest.mock: Mock object library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code></a> — mock object library<a class="headerlink" href="#module-unittest.mock" title="Permalink to this headline">¶</a></h1> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/unittest/mock.py">Lib/unittest/mock.py</a></p> <hr class="docutils" /> <p><a class="reference internal" href="#module-unittest.mock" title="unittest.mock: Mock object library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code></a> is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.</p> <p><a class="reference internal" href="#module-unittest.mock" title="unittest.mock: Mock object library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code></a> provides a core <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> class removing the need to create a host of stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way.</p> <p>Additionally, mock provides a <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> decorator that handles patching module and class level attributes within the scope of a test, along with <a class="reference internal" href="#unittest.mock.sentinel" title="unittest.mock.sentinel"><code class="xref py py-const docutils literal notranslate"><span class="pre">sentinel</span></code></a> for creating unique objects. See the <a class="reference internal" href="#quick-guide">quick guide</a> for some examples of how to use <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>, <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> and <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>.</p> <p>Mock is very easy to use and is designed for use with <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>. Mock is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks.</p> <p>There is a backport of <a class="reference internal" href="#module-unittest.mock" title="unittest.mock: Mock object library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code></a> for earlier versions of Python, available as <a class="reference external" href="https://pypi.org/project/mock">mock on PyPI</a>.</p> <div class="section" id="quick-guide"> <h2>Quick Guide<a class="headerlink" href="#quick-guide" title="Permalink to this headline">¶</a></h2> <p><a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> and <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> 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 available, and then make assertions about how they have been used:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">unittest.mock</span> <span class="k">import</span> <span class="n">MagicMock</span> <span class="gp">>>> </span><span class="n">thing</span> <span class="o">=</span> <span class="n">ProductionClass</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">thing</span><span class="o">.</span><span class="n">method</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">thing</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="s1">'value'</span><span class="p">)</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">thing</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="s1">'value'</span><span class="p">)</span> </pre></div> </div> <p><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> allows you to perform side effects, including raising an exception when a mock is called:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="ne">KeyError</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">))</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span>: <span class="n">'foo'</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">values</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'a'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">:</span> <span class="mi">3</span><span class="p">}</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">side_effect</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">values</span><span class="p">[</span><span class="n">arg</span><span class="p">]</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="n">side_effect</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="s1">'a'</span><span class="p">),</span> <span class="n">mock</span><span class="p">(</span><span class="s1">'b'</span><span class="p">),</span> <span class="n">mock</span><span class="p">(</span><span class="s1">'c'</span><span class="p">)</span> <span class="go">(1, 2, 3)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(),</span> <span class="n">mock</span><span class="p">(),</span> <span class="n">mock</span><span class="p">()</span> <span class="go">(5, 4, 3)</span> </pre></div> </div> <p>Mock has many other ways you can configure it and control its behaviour. For example the <em>spec</em> argument configures the mock to take its specification from another object. Attempting to access attributes or methods on the mock that don’t exist on the spec will fail with an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p> <p>The <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> 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:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">unittest.mock</span> <span class="k">import</span> <span class="n">patch</span> <span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'module.ClassName2'</span><span class="p">)</span> <span class="gp">... </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'module.ClassName1'</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">MockClass1</span><span class="p">,</span> <span class="n">MockClass2</span><span class="p">):</span> <span class="gp">... </span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName1</span><span class="p">()</span> <span class="gp">... </span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName2</span><span class="p">()</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">MockClass1</span> <span class="ow">is</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName1</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">MockClass2</span> <span class="ow">is</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName2</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">MockClass1</span><span class="o">.</span><span class="n">called</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">MockClass2</span><span class="o">.</span><span class="n">called</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> </pre></div> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal <em>Python</em> order that decorators are applied). This means from the bottom up, so in the example above the mock for <code class="docutils literal notranslate"><span class="pre">module.ClassName1</span></code> is passed in first.</p> <p>With <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read <a class="reference internal" href="#where-to-patch"><span class="std std-ref">where to patch</span></a>.</p> </div> <p>As well as a decorator <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> can be used as a context manager in a with statement:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">object</span><span class="p">(</span><span class="n">ProductionClass</span><span class="p">,</span> <span class="s1">'method'</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_method</span><span class="p">:</span> <span class="gp">... </span> <span class="n">thing</span> <span class="o">=</span> <span class="n">ProductionClass</span><span class="p">()</span> <span class="gp">... </span> <span class="n">thing</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock_method</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> </pre></div> </div> <p>There is also <a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">foo</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'key'</span><span class="p">:</span> <span class="s1">'value'</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">original</span> <span class="o">=</span> <span class="n">foo</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">dict</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="p">{</span><span class="s1">'newkey'</span><span class="p">:</span> <span class="s1">'newvalue'</span><span class="p">},</span> <span class="n">clear</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="p">{</span><span class="s1">'newkey'</span><span class="p">:</span> <span class="s1">'newvalue'</span><span class="p">}</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="n">original</span> </pre></div> </div> <p>Mock supports the mocking of Python <a class="reference internal" href="#magic-methods"><span class="std std-ref">magic methods</span></a>. The easiest way of using magic methods is with the <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> class. It allows you to do things like:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__str__</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'foobarbaz'</span> <span class="gp">>>> </span><span class="nb">str</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">'foobarbaz'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__str__</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">()</span> </pre></div> </div> <p>Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).</p> <p>The following is an example of using magic methods with the ordinary Mock class:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__str__</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="s1">'wheeeeee'</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">str</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">'wheeeeee'</span> </pre></div> </div> <p>For ensuring that the mock objects in your tests have the same api as the objects they are replacing, you can use <a class="reference internal" href="#auto-speccing"><span class="std std-ref">auto-speccing</span></a>. Auto-speccing can be done through the <em>autospec</em> argument to patch, or the <a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> function. Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object.</p> <p>This ensures that your mocks will fail in the same way as your production code if they are used incorrectly:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">unittest.mock</span> <span class="k">import</span> <span class="n">create_autospec</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock_function</span> <span class="o">=</span> <span class="n">create_autospec</span><span class="p">(</span><span class="n">function</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="s1">'fishy'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_function</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="go">'fishy'</span> <span class="gp">>>> </span><span class="n">mock_function</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_function</span><span class="p">(</span><span class="s1">'wrong arguments'</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">TypeError</span>: <span class="n"><lambda>() takes exactly 3 arguments (1 given)</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> can also be used on classes, where it copies the signature of the <code class="docutils literal notranslate"><span class="pre">__init__</span></code> method, and on callable objects where it copies the signature of the <code class="docutils literal notranslate"><span class="pre">__call__</span></code> method.</p> </div> <div class="section" id="the-mock-class"> <h2>The Mock Class<a class="headerlink" href="#the-mock-class" title="Permalink to this headline">¶</a></h2> <p><a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> 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 new mocks when you access them <a class="footnote-reference brackets" href="#id3" id="id1">1</a>. Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done to them.</p> <p><a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> is a subclass of <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> with all the magic methods pre-created and ready to use. There are also non-callable variants, useful when you are mocking out objects that aren’t callable: <a class="reference internal" href="#unittest.mock.NonCallableMock" title="unittest.mock.NonCallableMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">NonCallableMock</span></code></a> and <a class="reference internal" href="#unittest.mock.NonCallableMagicMock" title="unittest.mock.NonCallableMagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">NonCallableMagicMock</span></code></a></p> <p>The <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> decorators makes it easy to temporarily replace classes in a particular module with a <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> object. By default <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> will create a <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> for you. You can specify an alternative class of <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> using the <em>new_callable</em> argument to <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>.</p> <dl class="class"> <dt id="unittest.mock.Mock"> <em class="property">class </em><code class="descclassname">unittest.mock.</code><code class="descname">Mock</code><span class="sig-paren">(</span><em>spec=None</em>, <em>side_effect=None</em>, <em>return_value=DEFAULT</em>, <em>wraps=None</em>, <em>name=None</em>, <em>spec_set=None</em>, <em>unsafe=False</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock" title="Permalink to this definition">¶</a></dt> <dd><p>Create a new <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> object. <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> takes several optional arguments that specify the behaviour of the Mock object:</p> <ul> <li><p><em>spec</em>: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p> <p>If <em>spec</em> is an object (rather than a list of strings) then <a class="reference internal" href="stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> returns the class of the spec object. This allows mocks to pass <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> tests.</p> </li> <li><p><em>spec_set</em>: A stricter variant of <em>spec</em>. If used, attempting to <em>set</em> or get an attribute on the mock that isn’t on the object passed as <em>spec_set</em> will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p></li> <li><p><em>side_effect</em>: A function to be called whenever the Mock is called. See the <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a>, the return value of this function is used as the return value.</p> <p>Alternatively <em>side_effect</em> can be an exception class or instance. In this case the exception will be raised when the mock is called.</p> <p>If <em>side_effect</em> is an iterable then each call to the mock will return the next value from the iterable.</p> <p>A <em>side_effect</em> can be cleared by setting it to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p> </li> <li><p><em>return_value</em>: The value returned when the mock is called. By default this is a new Mock (created on first access). See the <a class="reference internal" href="#unittest.mock.Mock.return_value" title="unittest.mock.Mock.return_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code></a> attribute.</p></li> <li><p><em>unsafe</em>: By default if any attribute starts with <em>assert</em> or <em>assret</em> will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. Passing <code class="docutils literal notranslate"><span class="pre">unsafe=True</span></code> will allow access to these attributes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </li> <li><p><em>wraps</em>: Item for the mock object to wrap. If <em>wraps</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>).</p> <p>If the mock has an explicit <em>return_value</em> set then calls are not passed to the wrapped object and the <em>return_value</em> is returned instead.</p> </li> <li><p><em>name</em>: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks.</p></li> </ul> <p>Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. See the <a class="reference internal" href="#unittest.mock.Mock.configure_mock" title="unittest.mock.Mock.configure_mock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">configure_mock()</span></code></a> method for details.</p> <dl class="method"> <dt id="unittest.mock.Mock.assert_called"> <code class="descname">assert_called</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_called" title="Permalink to this definition">¶</a></dt> <dd><p>Assert that the mock was called at least once.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go"><Mock name='mock.method()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">assert_called</span><span class="p">()</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.assert_called_once"> <code class="descname">assert_called_once</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_called_once" title="Permalink to this definition">¶</a></dt> <dd><p>Assert that the mock was called exactly once.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go"><Mock name='mock.method()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">assert_called_once</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go"><Mock name='mock.method()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">assert_called_once</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected 'method' to have been called once. Called 2 times.</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.assert_called_with"> <code class="descname">assert_called_with</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_called_with" title="Permalink to this definition">¶</a></dt> <dd><p>This method is a convenient way of asserting that calls are made in a particular way:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">test</span><span class="o">=</span><span class="s1">'wow'</span><span class="p">)</span> <span class="go"><Mock name='mock.method()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">test</span><span class="o">=</span><span class="s1">'wow'</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.assert_called_once_with"> <code class="descname">assert_called_once_with</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_called_once_with" title="Permalink to this definition">¶</a></dt> <dd><p>Assert that the mock was called exactly once and that that call was with the specified arguments.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="s1">'baz'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="s1">'baz'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="s1">'other'</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="s1">'values'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'other'</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="s1">'values'</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected 'mock' to be called once. Called 2 times.</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.assert_any_call"> <code class="descname">assert_any_call</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_any_call" title="Permalink to this definition">¶</a></dt> <dd><p>assert the mock has been called with the specified arguments.</p> <p>The assert passes if the mock has <em>ever</em> been called, unlike <a class="reference internal" href="#unittest.mock.Mock.assert_called_with" title="unittest.mock.Mock.assert_called_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_with()</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.assert_called_once_with" title="unittest.mock.Mock.assert_called_once_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_once_with()</span></code></a> that only pass if the call is the most recent one, and in the case of <a class="reference internal" href="#unittest.mock.Mock.assert_called_once_with" title="unittest.mock.Mock.assert_called_once_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_once_with()</span></code></a> it must also be the only call.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">arg</span><span class="o">=</span><span class="s1">'thing'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="s1">'some'</span><span class="p">,</span> <span class="s1">'thing'</span><span class="p">,</span> <span class="s1">'else'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_any_call</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">arg</span><span class="o">=</span><span class="s1">'thing'</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.assert_has_calls"> <code class="descname">assert_has_calls</code><span class="sig-paren">(</span><em>calls</em>, <em>any_order=False</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_has_calls" title="Permalink to this definition">¶</a></dt> <dd><p>assert the mock has been called with the specified calls. The <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> list is checked for the calls.</p> <p>If <em>any_order</em> is false (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.</p> <p>If <em>any_order</em> is true then the calls can be in any order, but they must all appear in <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">calls</span> <span class="o">=</span> <span class="p">[</span><span class="n">call</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="n">call</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_has_calls</span><span class="p">(</span><span class="n">calls</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">calls</span> <span class="o">=</span> <span class="p">[</span><span class="n">call</span><span class="p">(</span><span class="mi">4</span><span class="p">),</span> <span class="n">call</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="n">call</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_has_calls</span><span class="p">(</span><span class="n">calls</span><span class="p">,</span> <span class="n">any_order</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.assert_not_called"> <code class="descname">assert_not_called</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.assert_not_called" title="Permalink to this definition">¶</a></dt> <dd><p>Assert the mock was never called.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">hello</span><span class="o">.</span><span class="n">assert_not_called</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">obj</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">hello</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">hello</span><span class="o">.</span><span class="n">assert_not_called</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected 'hello' to not have been called. Called 1 times.</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.reset_mock"> <code class="descname">reset_mock</code><span class="sig-paren">(</span><em>*</em>, <em>return_value=False</em>, <em>side_effect=False</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.reset_mock" title="Permalink to this definition">¶</a></dt> <dd><p>The reset_mock method resets all the call attributes on a mock object:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="s1">'hello'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">called</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">reset_mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">called</span> <span class="go">False</span> </pre></div> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added two keyword only argument to the reset_mock function.</p> </div> <p>This can be useful where you want to make a series of assertions that reuse the same object. Note that <a class="reference internal" href="#unittest.mock.Mock.reset_mock" title="unittest.mock.Mock.reset_mock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reset_mock()</span></code></a> <em>doesn’t</em> clear the return value, <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> or any child attributes you have set using normal assignment by default. In case you want to reset <em>return_value</em> or <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a>, then pass the corresponding parameter as <code class="docutils literal notranslate"><span class="pre">True</span></code>. Child mocks and the return value mock (if any) are reset as well.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><em>return_value</em>, and <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> are keyword only argument.</p> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.mock_add_spec"> <code class="descname">mock_add_spec</code><span class="sig-paren">(</span><em>spec</em>, <em>spec_set=False</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.mock_add_spec" title="Permalink to this definition">¶</a></dt> <dd><p>Add a spec to a mock. <em>spec</em> can either be an object or a list of strings. Only attributes on the <em>spec</em> can be fetched as attributes from the mock.</p> <p>If <em>spec_set</em> is true then only attributes on the spec can be set.</p> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.attach_mock"> <code class="descname">attach_mock</code><span class="sig-paren">(</span><em>mock</em>, <em>attribute</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.attach_mock" title="Permalink to this definition">¶</a></dt> <dd><p>Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the <a class="reference internal" href="#unittest.mock.Mock.method_calls" title="unittest.mock.Mock.method_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method_calls</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> attributes of this one.</p> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.configure_mock"> <code class="descname">configure_mock</code><span class="sig-paren">(</span><em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.configure_mock" title="Permalink to this definition">¶</a></dt> <dd><p>Set attributes on the mock through keyword arguments.</p> <p>Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">attrs</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'method.return_value'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'other.side_effect'</span><span class="p">:</span> <span class="ne">KeyError</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">configure_mock</span><span class="p">(</span><span class="o">**</span><span class="n">attrs</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">other</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span> </pre></div> </div> <p>The same thing can be achieved in the constructor call to mocks:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">attrs</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'method.return_value'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'other.side_effect'</span><span class="p">:</span> <span class="ne">KeyError</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">some_attribute</span><span class="o">=</span><span class="s1">'eggs'</span><span class="p">,</span> <span class="o">**</span><span class="n">attrs</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">some_attribute</span> <span class="go">'eggs'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">other</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.Mock.configure_mock" title="unittest.mock.Mock.configure_mock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">configure_mock()</span></code></a> exists to make it easier to do configuration after the mock has been created.</p> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock.__dir__"> <code class="descname">__dir__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock.__dir__" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> objects limit the results of <code class="docutils literal notranslate"><span class="pre">dir(some_mock)</span></code> to useful results. For mocks with a <em>spec</em> this includes all the permitted attributes for the mock.</p> <p>See <a class="reference internal" href="#unittest.mock.FILTER_DIR" title="unittest.mock.FILTER_DIR"><code class="xref py py-data docutils literal notranslate"><span class="pre">FILTER_DIR</span></code></a> for what this filtering does, and how to switch it off.</p> </dd></dl> <dl class="method"> <dt id="unittest.mock.Mock._get_child_mock"> <code class="descname">_get_child_mock</code><span class="sig-paren">(</span><em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.Mock._get_child_mock" title="Permalink to this definition">¶</a></dt> <dd><p>Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.</p> <p>For non-callable mocks the callable variant will be used (rather than any custom subclass).</p> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.called"> <code class="descname">called</code><a class="headerlink" href="#unittest.mock.Mock.called" title="Permalink to this definition">¶</a></dt> <dd><p>A boolean representing whether or not the mock object has been called:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">called</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">called</span> <span class="go">True</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.call_count"> <code class="descname">call_count</code><a class="headerlink" href="#unittest.mock.Mock.call_count" title="Permalink to this definition">¶</a></dt> <dd><p>An integer telling you how many times the mock object has been called:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_count</span> <span class="go">0</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_count</span> <span class="go">2</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.return_value"> <code class="descname">return_value</code><a class="headerlink" href="#unittest.mock.Mock.return_value" title="Permalink to this definition">¶</a></dt> <dd><p>Set this to configure the value returned by calling the mock:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'fish'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="go">'fish'</span> </pre></div> </div> <p>The default return value is a mock object and you can configure it in the normal way:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">return_value</span><span class="o">.</span><span class="n">attribute</span> <span class="o">=</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">Attribute</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">return_value</span><span class="p">()</span> <span class="go"><Mock name='mock()()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">return_value</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">()</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.Mock.return_value" title="unittest.mock.Mock.return_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code></a> can also be set in the constructor:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">return_value</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="go">3</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.side_effect"> <code class="descname">side_effect</code><a class="headerlink" href="#unittest.mock.Mock.side_effect" title="Permalink to this definition">¶</a></dt> <dd><p>This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised.</p> <p>If you pass in a function it will be called with same arguments as the mock and unless the function returns the <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a> singleton the call to the mock will then return whatever the function returns. If the function returns <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a> then the mock will return its normal value (from the <a class="reference internal" href="#unittest.mock.Mock.return_value" title="unittest.mock.Mock.return_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code></a>).</p> <p>If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock (<a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a> handling is identical to the function case).</p> <p>An example of a mock that raises an exception (to test exception handling of an API):</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">'Boom!'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">Exception</span>: <span class="n">Boom!</span> </pre></div> </div> <p>Using <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> to return a sequence of values:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(),</span> <span class="n">mock</span><span class="p">(),</span> <span class="n">mock</span><span class="p">()</span> <span class="go">(3, 2, 1)</span> </pre></div> </div> <p>Using a callable:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">side_effect</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">DEFAULT</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="n">side_effect</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="go">3</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> can be set in the constructor. Here’s an example that adds one to the value the mock is called with and returns it:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">side_effect</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">value</span><span class="p">:</span> <span class="n">value</span> <span class="o">+</span> <span class="mi">1</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="n">side_effect</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="go">4</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="o">-</span><span class="mi">8</span><span class="p">)</span> <span class="go">-7</span> </pre></div> </div> <p>Setting <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> to <code class="docutils literal notranslate"><span class="pre">None</span></code> clears it:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="ne">KeyError</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="kc">None</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">3</span> </pre></div> </div> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.call_args"> <code class="descname">call_args</code><a class="headerlink" href="#unittest.mock.Mock.call_args" title="Permalink to this definition">¶</a></dt> <dd><p>This is either <code class="docutils literal notranslate"><span class="pre">None</span></code> (if the mock hasn’t been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member is any ordered arguments the mock was called with (or an empty tuple) and the second member is any keyword arguments (or an empty dictionary).</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">mock</span><span class="o">.</span><span class="n">call_args</span><span class="p">)</span> <span class="go">None</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args</span> <span class="go">call()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args</span> <span class="o">==</span> <span class="p">()</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args</span> <span class="go">call(3, 4)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args</span> <span class="o">==</span> <span class="p">((</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),)</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="s1">'fish'</span><span class="p">,</span> <span class="nb">next</span><span class="o">=</span><span class="s1">'w00t!'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args</span> <span class="go">call(3, 4, 5, key='fish', next='w00t!')</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.Mock.call_args" title="unittest.mock.Mock.call_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args</span></code></a>, along with members of the lists <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args_list</span></code></a>, <a class="reference internal" href="#unittest.mock.Mock.method_calls" title="unittest.mock.Mock.method_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method_calls</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> are <a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> objects. These are tuples, so they can be unpacked to get at the individual arguments and make more complex assertions. See <a class="reference internal" href="#calls-as-tuples"><span class="std std-ref">calls as tuples</span></a>.</p> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.call_args_list"> <code class="descname">call_args_list</code><a class="headerlink" href="#unittest.mock.Mock.call_args_list" title="Permalink to this definition">¶</a></dt> <dd><p>This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list. The <a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> object can be used for conveniently constructing lists of calls to compare with <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args_list</span></code></a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="s1">'fish'</span><span class="p">,</span> <span class="nb">next</span><span class="o">=</span><span class="s1">'w00t!'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args_list</span> <span class="go">[call(), call(3, 4), call(key='fish', next='w00t!')]</span> <span class="gp">>>> </span><span class="n">expected</span> <span class="o">=</span> <span class="p">[(),</span> <span class="p">((</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),),</span> <span class="p">({</span><span class="s1">'key'</span><span class="p">:</span> <span class="s1">'fish'</span><span class="p">,</span> <span class="s1">'next'</span><span class="p">:</span> <span class="s1">'w00t!'</span><span class="p">},)]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">call_args_list</span> <span class="o">==</span> <span class="n">expected</span> <span class="go">True</span> </pre></div> </div> <p>Members of <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args_list</span></code></a> are <a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> objects. These can be unpacked as tuples to get at the individual arguments. See <a class="reference internal" href="#calls-as-tuples"><span class="std std-ref">calls as tuples</span></a>.</p> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.method_calls"> <code class="descname">method_calls</code><a class="headerlink" href="#unittest.mock.Mock.method_calls" title="Permalink to this definition">¶</a></dt> <dd><p>As well as tracking calls to themselves, mocks also track calls to methods and attributes, and <em>their</em> methods and attributes:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go"><Mock name='mock.method()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">property</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">attribute</span><span class="p">()</span> <span class="go"><Mock name='mock.property.method.attribute()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method_calls</span> <span class="go">[call.method(), call.property.method.attribute()]</span> </pre></div> </div> <p>Members of <a class="reference internal" href="#unittest.mock.Mock.method_calls" title="unittest.mock.Mock.method_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method_calls</span></code></a> are <a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> objects. These can be unpacked as tuples to get at the individual arguments. See <a class="reference internal" href="#calls-as-tuples"><span class="std std-ref">calls as tuples</span></a>.</p> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.mock_calls"> <code class="descname">mock_calls</code><a class="headerlink" href="#unittest.mock.Mock.mock_calls" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> records <em>all</em> calls to the mock object, its methods, magic methods <em>and</em> return value mocks.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">result</span> <span class="o">=</span> <span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">first</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="go"><MagicMock name='mock.first()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">second</span><span class="p">()</span> <span class="go"><MagicMock name='mock.second()' id='...'></span> <span class="gp">>>> </span><span class="nb">int</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">1</span> <span class="gp">>>> </span><span class="n">result</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="go"><MagicMock name='mock()()' id='...'></span> <span class="gp">>>> </span><span class="n">expected</span> <span class="o">=</span> <span class="p">[</span><span class="n">call</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">call</span><span class="o">.</span><span class="n">first</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">),</span> <span class="n">call</span><span class="o">.</span><span class="n">second</span><span class="p">(),</span> <span class="gp">... </span><span class="n">call</span><span class="o">.</span><span class="fm">__int__</span><span class="p">(),</span> <span class="n">call</span><span class="p">()(</span><span class="mi">1</span><span class="p">)]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">mock_calls</span> <span class="o">==</span> <span class="n">expected</span> <span class="go">True</span> </pre></div> </div> <p>Members of <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> are <a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> objects. These can be unpacked as tuples to get at the individual arguments. See <a class="reference internal" href="#calls-as-tuples"><span class="std std-ref">calls as tuples</span></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The way <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> are recorded means that where nested calls are made, the parameters of ancestor calls are not recorded and so will always compare equal:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">top</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span><span class="o">.</span><span class="n">bottom</span><span class="p">()</span> <span class="go"><MagicMock name='mock.top().bottom()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call.top(a=3), call.top().bottom()]</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">mock_calls</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="n">call</span><span class="o">.</span><span class="n">top</span><span class="p">(</span><span class="n">a</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">bottom</span><span class="p">()</span> <span class="go">True</span> </pre></div> </div> </div> </dd></dl> <dl class="attribute"> <dt id="unittest.mock.Mock.__class__"> <code class="descname">__class__</code><a class="headerlink" href="#unittest.mock.Mock.__class__" title="Permalink to this definition">¶</a></dt> <dd><p>Normally the <a class="reference internal" href="#unittest.mock.Mock.__class__" title="unittest.mock.Mock.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> attribute of an object will return its type. For a mock object with a <code class="xref py py-attr docutils literal notranslate"><span class="pre">spec</span></code>, <code class="docutils literal notranslate"><span class="pre">__class__</span></code> returns the spec class instead. This allows mock objects to pass <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> tests for the object they are replacing / masquerading as:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">spec</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">mock</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.Mock.__class__" title="unittest.mock.Mock.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> is assignable to, this allows a mock to pass an <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> check without forcing you to use a spec:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="vm">__class__</span> <span class="o">=</span> <span class="nb">dict</span> <span class="gp">>>> </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">mock</span><span class="p">,</span> <span class="nb">dict</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> </dd></dl> </dd></dl> <dl class="class"> <dt id="unittest.mock.NonCallableMock"> <em class="property">class </em><code class="descclassname">unittest.mock.</code><code class="descname">NonCallableMock</code><span class="sig-paren">(</span><em>spec=None</em>, <em>wraps=None</em>, <em>name=None</em>, <em>spec_set=None</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.NonCallableMock" title="Permalink to this definition">¶</a></dt> <dd><p>A non-callable version of <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>. The constructor parameters have the same meaning of <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>, with the exception of <em>return_value</em> and <em>side_effect</em> which have no meaning on a non-callable mock.</p> </dd></dl> <p>Mock objects that use a class or an instance as a <code class="xref py py-attr docutils literal notranslate"><span class="pre">spec</span></code> or <code class="xref py py-attr docutils literal notranslate"><span class="pre">spec_set</span></code> are able to pass <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> tests:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">spec</span><span class="o">=</span><span class="n">SomeClass</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">mock</span><span class="p">,</span> <span class="n">SomeClass</span><span class="p">)</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">spec_set</span><span class="o">=</span><span class="n">SomeClass</span><span class="p">())</span> <span class="gp">>>> </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">mock</span><span class="p">,</span> <span class="n">SomeClass</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p>The <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> classes have support for mocking magic methods. See <a class="reference internal" href="#magic-methods"><span class="std std-ref">magic methods</span></a> for the full details.</p> <p>The mock classes and the <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> decorators all take arbitrary keyword arguments for configuration. For the <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> decorators the keywords are passed to the constructor of the mock being created. The keyword arguments are for configuring attributes of the mock:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">attribute</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">other</span><span class="o">=</span><span class="s1">'fish'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">attribute</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">other</span> <span class="go">'fish'</span> </pre></div> </div> <p>The return value and side effect of child mocks can be set in the same way, using dotted notation. As you can’t use dotted names directly in a call you have to create a dictionary and unpack it using <code class="docutils literal notranslate"><span class="pre">**</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">attrs</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'method.return_value'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'other.side_effect'</span><span class="p">:</span> <span class="ne">KeyError</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">some_attribute</span><span class="o">=</span><span class="s1">'eggs'</span><span class="p">,</span> <span class="o">**</span><span class="n">attrs</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">some_attribute</span> <span class="go">'eggs'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">other</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span> </pre></div> </div> <p>A callable mock which was created with a <em>spec</em> (or a <em>spec_set</em>) will introspect the specification object’s signature when matching calls to the mock. Therefore, it can match the actual call’s arguments regardless of whether they were passed positionally or by name:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">spec</span><span class="o">=</span><span class="n">f</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="go"><Mock name='mock()' id='140161580456576'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> </pre></div> </div> <p>This applies to <a class="reference internal" href="#unittest.mock.Mock.assert_called_with" title="unittest.mock.Mock.assert_called_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_with()</span></code></a>, <a class="reference internal" href="#unittest.mock.Mock.assert_called_once_with" title="unittest.mock.Mock.assert_called_once_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_once_with()</span></code></a>, <a class="reference internal" href="#unittest.mock.Mock.assert_has_calls" title="unittest.mock.Mock.assert_has_calls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_has_calls()</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.assert_any_call" title="unittest.mock.Mock.assert_any_call"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_any_call()</span></code></a>. When <a class="reference internal" href="#auto-speccing"><span class="std std-ref">Autospeccing</span></a>, it will also apply to method calls on the mock object.</p> <blockquote> <div><div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Added signature introspection on specced and autospecced mock objects.</p> </div> </div></blockquote> <dl class="class"> <dt id="unittest.mock.PropertyMock"> <em class="property">class </em><code class="descclassname">unittest.mock.</code><code class="descname">PropertyMock</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.PropertyMock" title="Permalink to this definition">¶</a></dt> <dd><p>A mock intended to be used as a property, or other descriptor, on a class. <a class="reference internal" href="#unittest.mock.PropertyMock" title="unittest.mock.PropertyMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">PropertyMock</span></code></a> provides <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> methods so you can specify a return value when it is fetched.</p> <p>Fetching a <a class="reference internal" href="#unittest.mock.PropertyMock" title="unittest.mock.PropertyMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">PropertyMock</span></code></a> instance from an object calls the mock, with no args. Setting it calls the mock with the value being set.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="gp">... </span> <span class="nd">@property</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="s1">'something'</span> <span class="gp">... </span> <span class="nd">@foo</span><span class="o">.</span><span class="n">setter</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Foo.foo'</span><span class="p">,</span> <span class="n">new_callable</span><span class="o">=</span><span class="n">PropertyMock</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_foo</span><span class="p">:</span> <span class="gp">... </span> <span class="n">mock_foo</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'mockity-mock'</span> <span class="gp">... </span> <span class="n">this_foo</span> <span class="o">=</span> <span class="n">Foo</span><span class="p">()</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">this_foo</span><span class="o">.</span><span class="n">foo</span><span class="p">)</span> <span class="gp">... </span> <span class="n">this_foo</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="mi">6</span> <span class="gp">...</span> <span class="go">mockity-mock</span> <span class="gp">>>> </span><span class="n">mock_foo</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call(), call(6)]</span> </pre></div> </div> </dd></dl> <p>Because of the way mock attributes are stored you can’t directly attach a <a class="reference internal" href="#unittest.mock.PropertyMock" title="unittest.mock.PropertyMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">PropertyMock</span></code></a> to a mock object. Instead you can attach it to the mock type object:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">PropertyMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">type</span><span class="p">(</span><span class="n">m</span><span class="p">)</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="n">p</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">foo</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">()</span> </pre></div> </div> <div class="section" id="calling"> <h3>Calling<a class="headerlink" href="#calling" title="Permalink to this headline">¶</a></h3> <p>Mock objects are callable. The call will return the value set as the <a class="reference internal" href="#unittest.mock.Mock.return_value" title="unittest.mock.Mock.return_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code></a> attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.</p> <p>Calls made to the object will be recorded in the attributes like <a class="reference internal" href="#unittest.mock.Mock.call_args" title="unittest.mock.Mock.call_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args_list</span></code></a>.</p> <p>If <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> is set then it will be called after the call has been recorded, so if <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> raises an exception the call is still recorded.</p> <p>The simplest way to make a mock raise an exception when called is to make <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> an exception class or instance:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="ne">IndexError</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">IndexError</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call(1, 2, 3)]</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="ne">KeyError</span><span class="p">(</span><span class="s1">'Bang!'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">,</span> <span class="s1">'four'</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span>: <span class="n">'Bang!'</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call(1, 2, 3), call('two', 'three', 'four')]</span> </pre></div> </div> <p>If <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> is a function then whatever that function returns is what calls to the mock return. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">side_effect</span><span class="p">(</span><span class="n">value</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">value</span> <span class="o">+</span> <span class="mi">1</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="n">side_effect</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="go">2</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call(1), call(2)]</span> </pre></div> </div> <p>If you want the mock to still return the default return value (a new mock), or any set return value, then there are two ways of doing this. Either return <code class="xref py py-attr docutils literal notranslate"><span class="pre">mock.return_value</span></code> from inside <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code>, or return <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">side_effect</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">m</span><span class="o">.</span><span class="n">return_value</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="n">side_effect</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="mi">3</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">side_effect</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">DEFAULT</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="n">side_effect</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">3</span> </pre></div> </div> <p>To remove a <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code>, and return to the default behaviour, set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="mi">6</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">side_effect</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="mi">3</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="n">side_effect</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="kc">None</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">6</span> </pre></div> </div> <p>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a <a class="reference internal" href="exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> is raised):</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">1</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">2</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">StopIteration</span> </pre></div> </div> <p>If any members of the iterable are exceptions they will be raised instead of returned:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">iterable</span> <span class="o">=</span> <span class="p">(</span><span class="mi">33</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">,</span> <span class="mi">66</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="n">iterable</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">33</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">ValueError</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="go">66</span> </pre></div> </div> </div> <div class="section" id="deleting-attributes"> <span id="id2"></span><h3>Deleting Attributes<a class="headerlink" href="#deleting-attributes" title="Permalink to this headline">¶</a></h3> <p>Mock objects create attributes on demand. This allows them to pretend to be objects of any type.</p> <p>You may want a mock object to return <code class="docutils literal notranslate"><span class="pre">False</span></code> to a <a class="reference internal" href="functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> call, or raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> when an attribute is fetched. You can do this by providing an object as a <code class="xref py py-attr docutils literal notranslate"><span class="pre">spec</span></code> for a mock, but that isn’t always convenient.</p> <p>You “block” attributes by deleting them. Once deleted, accessing an attribute will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">mock</span><span class="p">,</span> <span class="s1">'m'</span><span class="p">)</span> <span class="go">True</span> <span class="gp">>>> </span><span class="k">del</span> <span class="n">mock</span><span class="o">.</span><span class="n">m</span> <span class="gp">>>> </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">mock</span><span class="p">,</span> <span class="s1">'m'</span><span class="p">)</span> <span class="go">False</span> <span class="gp">>>> </span><span class="k">del</span> <span class="n">mock</span><span class="o">.</span><span class="n">f</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">f</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AttributeError</span>: <span class="n">f</span> </pre></div> </div> </div> <div class="section" id="mock-names-and-the-name-attribute"> <h3>Mock names and the name attribute<a class="headerlink" href="#mock-names-and-the-name-attribute" title="Permalink to this headline">¶</a></h3> <p>Since “name” is an argument to the <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> constructor, if you want your mock object to have a “name” attribute you can’t just pass it in at creation time. There are two alternatives. One option is to use <a class="reference internal" href="#unittest.mock.Mock.configure_mock" title="unittest.mock.Mock.configure_mock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">configure_mock()</span></code></a>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">configure_mock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'my_name'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">name</span> <span class="go">'my_name'</span> </pre></div> </div> <p>A simpler option is to simply set the “name” attribute after mock creation:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s2">"foo"</span> </pre></div> </div> </div> <div class="section" id="attaching-mocks-as-attributes"> <h3>Attaching Mocks as Attributes<a class="headerlink" href="#attaching-mocks-as-attributes" title="Permalink to this headline">¶</a></h3> <p>When you attach a mock as an attribute of another mock (or as the return value) it becomes a “child” of that mock. Calls to the child are recorded in the <a class="reference internal" href="#unittest.mock.Mock.method_calls" title="unittest.mock.Mock.method_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method_calls</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> attributes of the parent. This is useful for configuring child mocks and then attaching them to the parent, or for attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">parent</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">child1</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">child2</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">parent</span><span class="o">.</span><span class="n">child1</span> <span class="o">=</span> <span class="n">child1</span> <span class="gp">>>> </span><span class="n">parent</span><span class="o">.</span><span class="n">child2</span> <span class="o">=</span> <span class="n">child2</span> <span class="gp">>>> </span><span class="n">child1</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">child2</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">parent</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call.child1(1), call.child2(2)]</span> </pre></div> </div> <p>The exception to this is if the mock has a name. This allows you to prevent the “parenting” if for some reason you don’t want it to happen.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">not_a_child</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'not-a-child'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">attribute</span> <span class="o">=</span> <span class="n">not_a_child</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">attribute</span><span class="p">()</span> <span class="go"><MagicMock name='not-a-child()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[]</span> </pre></div> </div> <p>Mocks created for you by <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> are automatically given names. To attach mocks that have names to a parent you use the <a class="reference internal" href="#unittest.mock.Mock.attach_mock" title="unittest.mock.Mock.attach_mock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">attach_mock()</span></code></a> method:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">thing1</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">thing2</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">parent</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.thing1'</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="k">as</span> <span class="n">child1</span><span class="p">:</span> <span class="gp">... </span> <span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.thing2'</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="k">as</span> <span class="n">child2</span><span class="p">:</span> <span class="gp">... </span> <span class="n">parent</span><span class="o">.</span><span class="n">attach_mock</span><span class="p">(</span><span class="n">child1</span><span class="p">,</span> <span class="s1">'child1'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">parent</span><span class="o">.</span><span class="n">attach_mock</span><span class="p">(</span><span class="n">child2</span><span class="p">,</span> <span class="s1">'child2'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">child1</span><span class="p">(</span><span class="s1">'one'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">child2</span><span class="p">(</span><span class="s1">'two'</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">parent</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call.child1('one'), call.child2('two')]</span> </pre></div> </div> <dl class="footnote brackets"> <dt class="label" id="id3"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt> <dd><p>The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. This is because the interpreter will often implicitly request these methods, and gets <em>very</em> confused to get a new Mock object when it expects a magic method. If you need magic method support see <a class="reference internal" href="#magic-methods"><span class="std std-ref">magic methods</span></a>.</p> </dd> </dl> </div> </div> <div class="section" id="the-patchers"> <h2>The patchers<a class="headerlink" href="#the-patchers" title="Permalink to this headline">¶</a></h2> <p>The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.</p> <div class="section" id="patch"> <h3>patch<a class="headerlink" href="#patch" title="Permalink to this headline">¶</a></h3> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> is straightforward to use. The key is to do the patching in the right namespace. See the section <a class="reference internal" href="#id5">where to patch</a>.</p> </div> <dl class="function"> <dt id="unittest.mock.patch"> <code class="descclassname">unittest.mock.</code><code class="descname">patch</code><span class="sig-paren">(</span><em>target</em>, <em>new=DEFAULT</em>, <em>spec=None</em>, <em>create=False</em>, <em>spec_set=None</em>, <em>autospec=None</em>, <em>new_callable=None</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.patch" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the <em>target</em> is patched with a <em>new</em> object. When the function/with statement exits the patch is undone.</p> <p>If <em>new</em> is omitted, then the target is replaced with a <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a>. If <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> is used as a decorator and <em>new</em> is omitted, the created mock is passed in as an extra argument to the decorated function. If <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> is used as a context manager the created mock is returned by the context manager.</p> <p><em>target</em> should be a string in the form <code class="docutils literal notranslate"><span class="pre">'package.module.ClassName'</span></code>. The <em>target</em> is imported and the specified object replaced with the <em>new</em> object, so the <em>target</em> must be importable from the environment you are calling <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> from. The target is imported when the decorated function is executed, not at decoration time.</p> <p>The <em>spec</em> and <em>spec_set</em> keyword arguments are passed to the <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> if patch is creating one for you.</p> <p>In addition you can pass <code class="docutils literal notranslate"><span class="pre">spec=True</span></code> or <code class="docutils literal notranslate"><span class="pre">spec_set=True</span></code>, which causes patch to pass in the object being mocked as the spec/spec_set object.</p> <p><em>new_callable</em> allows you to specify a different class, or callable object, that will be called to create the <em>new</em> object. By default <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> is used.</p> <p>A more powerful form of <em>spec</em> is <em>autospec</em>. If you set <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the <a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> function and <a class="reference internal" href="#auto-speccing"><span class="std std-ref">Autospeccing</span></a>.</p> <p>Instead of <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> you can pass <code class="docutils literal notranslate"><span class="pre">autospec=some_object</span></code> to use an arbitrary object as the spec instead of the one being replaced.</p> <p>By default <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> will fail to replace attributes that don’t exist. If you pass in <code class="docutils literal notranslate"><span class="pre">create=True</span></code>, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!</p> <div class="admonition note"> <p class="admonition-title">Note</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>If you are patching builtins in a module then you don’t need to pass <code class="docutils literal notranslate"><span class="pre">create=True</span></code>, it will be added by default.</p> </div> </div> <p>Patch can be used as a <code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code> class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> finds tests by looking for method names that start with <code class="docutils literal notranslate"><span class="pre">patch.TEST_PREFIX</span></code>. By default this is <code class="docutils literal notranslate"><span class="pre">'test'</span></code>, which matches the way <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> finds tests. You can specify an alternative prefix by setting <code class="docutils literal notranslate"><span class="pre">patch.TEST_PREFIX</span></code>.</p> <p>Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use “as” then the patched object will be bound to the name after the “as”; very useful if <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> is creating a mock object for you.</p> <p><a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> takes arbitrary keyword arguments. These will be passed to the <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> (or <em>new_callable</em>) on construction.</p> <p><code class="docutils literal notranslate"><span class="pre">patch.dict(...)</span></code>, <code class="docutils literal notranslate"><span class="pre">patch.multiple(...)</span></code> and <code class="docutils literal notranslate"><span class="pre">patch.object(...)</span></code> are available for alternate use-cases.</p> </dd></dl> <p><a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> as function decorator, creating the mock for you and passing it into the decorated function:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'__main__.SomeClass'</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">normal_argument</span><span class="p">,</span> <span class="n">mock_class</span><span class="p">):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">mock_class</span> <span class="ow">is</span> <span class="n">SomeClass</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">function</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p>Patching a class replaces the class with a <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> <em>instance</em>. If the class is instantiated in the code under test then it will be the <a class="reference internal" href="#unittest.mock.Mock.return_value" title="unittest.mock.Mock.return_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code></a> of the mock that will be used.</p> <p>If the class is instantiated multiple times you could use <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> to return a new mock each time. Alternatively you can set the <em>return_value</em> to be anything you want.</p> <p>To configure return values on methods of <em>instances</em> on the patched class you must do this on the <code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code>. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Class</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Class'</span><span class="p">)</span> <span class="k">as</span> <span class="n">MockClass</span><span class="p">:</span> <span class="gp">... </span> <span class="n">instance</span> <span class="o">=</span> <span class="n">MockClass</span><span class="o">.</span><span class="n">return_value</span> <span class="gp">... </span> <span class="n">instance</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'foo'</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">Class</span><span class="p">()</span> <span class="ow">is</span> <span class="n">instance</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">Class</span><span class="p">()</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="o">==</span> <span class="s1">'foo'</span> <span class="gp">...</span> </pre></div> </div> <p>If you use <em>spec</em> or <em>spec_set</em> and <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> is replacing a <em>class</em>, then the return value of the created mock will have the same spec.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Original</span> <span class="o">=</span> <span class="n">Class</span> <span class="gp">>>> </span><span class="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Class'</span><span class="p">,</span> <span class="n">spec</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">MockClass</span> <span class="o">=</span> <span class="n">patcher</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">instance</span> <span class="o">=</span> <span class="n">MockClass</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">Original</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">patcher</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span> </pre></div> </div> <p>The <em>new_callable</em> argument is useful where you want to use an alternative class to the default <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> for the created mock. For example, if you wanted a <a class="reference internal" href="#unittest.mock.NonCallableMock" title="unittest.mock.NonCallableMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">NonCallableMock</span></code></a> to be used:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">thing</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.thing'</span><span class="p">,</span> <span class="n">new_callable</span><span class="o">=</span><span class="n">NonCallableMock</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_thing</span><span class="p">:</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">thing</span> <span class="ow">is</span> <span class="n">mock_thing</span> <span class="gp">... </span> <span class="n">thing</span><span class="p">()</span> <span class="gp">...</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">TypeError</span>: <span class="n">'NonCallableMock' object is not callable</span> </pre></div> </div> <p>Another use case might be to replace an object with an <a class="reference internal" href="io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> instance:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">io</span> <span class="k">import</span> <span class="n">StringIO</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Something'</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'sys.stdout'</span><span class="p">,</span> <span class="n">new_callable</span><span class="o">=</span><span class="n">StringIO</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">mock_stdout</span><span class="p">):</span> <span class="gp">... </span> <span class="n">foo</span><span class="p">()</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mock_stdout</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span> <span class="o">==</span> <span class="s1">'Something</span><span class="se">\n</span><span class="s1">'</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> </pre></div> </div> <p>When <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> 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:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.thing'</span><span class="p">,</span> <span class="n">first</span><span class="o">=</span><span class="s1">'one'</span><span class="p">,</span> <span class="n">second</span><span class="o">=</span><span class="s1">'two'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_thing</span> <span class="o">=</span> <span class="n">patcher</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock_thing</span><span class="o">.</span><span class="n">first</span> <span class="go">'one'</span> <span class="gp">>>> </span><span class="n">mock_thing</span><span class="o">.</span><span class="n">second</span> <span class="go">'two'</span> </pre></div> </div> <p>As well as attributes on the created mock attributes, like the <a class="reference internal" href="#unittest.mock.Mock.return_value" title="unittest.mock.Mock.return_value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">return_value</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a>, 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 <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> call using <code class="docutils literal notranslate"><span class="pre">**</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'method.return_value'</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'other.side_effect'</span><span class="p">:</span> <span class="ne">KeyError</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.thing'</span><span class="p">,</span> <span class="o">**</span><span class="n">config</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_thing</span> <span class="o">=</span> <span class="n">patcher</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock_thing</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">mock_thing</span><span class="o">.</span><span class="n">other</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">KeyError</span> </pre></div> </div> <p>By default, attempting to patch a function in a module (or a method or an attribute in a class) that does not exist will fail with <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'sys.non_existing_attribute'</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">():</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">sys</span><span class="o">.</span><span class="n">non_existing_attribute</span> <span class="o">==</span> <span class="mi">42</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AttributeError</span>: <span class="n"><module 'sys' (built-in)> does not have the attribute 'non_existing'</span> </pre></div> </div> <p>but adding <code class="docutils literal notranslate"><span class="pre">create=True</span></code> in the call to <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> will make the previous example work as expected:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'sys.non_existing_attribute'</span><span class="p">,</span> <span class="mi">42</span><span class="p">,</span> <span class="n">create</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">mock_stdout</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">sys</span><span class="o">.</span><span class="n">non_existing_attribute</span> <span class="o">==</span> <span class="mi">42</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> </pre></div> </div> </div> <div class="section" id="patch-object"> <h3>patch.object<a class="headerlink" href="#patch-object" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.patch.object"> <code class="descclassname">patch.</code><code class="descname">object</code><span class="sig-paren">(</span><em>target</em>, <em>attribute</em>, <em>new=DEFAULT</em>, <em>spec=None</em>, <em>create=False</em>, <em>spec_set=None</em>, <em>autospec=None</em>, <em>new_callable=None</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.patch.object" title="Permalink to this definition">¶</a></dt> <dd><p>patch the named member (<em>attribute</em>) on an object (<em>target</em>) with a mock object.</p> <p><a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> can be used as a decorator, class decorator or a context manager. Arguments <em>new</em>, <em>spec</em>, <em>create</em>, <em>spec_set</em>, <em>autospec</em> and <em>new_callable</em> have the same meaning as for <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>. Like <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>, <a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> takes arbitrary keyword arguments for configuring the mock object it creates.</p> <p>When used as a class decorator <a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> honours <code class="docutils literal notranslate"><span class="pre">patch.TEST_PREFIX</span></code> for choosing which methods to wrap.</p> </dd></dl> <p>You can either call <a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.</p> <p>When calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="o">.</span><span class="n">object</span><span class="p">(</span><span class="n">SomeClass</span><span class="p">,</span> <span class="s1">'class_method'</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">mock_method</span><span class="p">):</span> <span class="gp">... </span> <span class="n">SomeClass</span><span class="o">.</span><span class="n">class_method</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">... </span> <span class="n">mock_method</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> </pre></div> </div> <p><em>spec</em>, <em>create</em> and the other arguments to <a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> have the same meaning as they do for <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>.</p> </div> <div class="section" id="patch-dict"> <h3>patch.dict<a class="headerlink" href="#patch-dict" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.patch.dict"> <code class="descclassname">patch.</code><code class="descname">dict</code><span class="sig-paren">(</span><em>in_dict</em>, <em>values=()</em>, <em>clear=False</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.patch.dict" title="Permalink to this definition">¶</a></dt> <dd><p>Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test.</p> <p><em>in_dict</em> can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys.</p> <p><em>in_dict</em> can also be a string specifying the name of the dictionary, which will then be fetched by importing it.</p> <p><em>values</em> can be a dictionary of values to set in the dictionary. <em>values</em> can also be an iterable of <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.</p> <p>If <em>clear</em> is true then the dictionary will be cleared before the new values are set.</p> <p><a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> can also be called with arbitrary keyword arguments to set values in the dictionary.</p> <p><a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> can be used as a context manager, decorator or class decorator. When used as a class decorator <a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> honours <code class="docutils literal notranslate"><span class="pre">patch.TEST_PREFIX</span></code> for choosing which methods to wrap.</p> </dd></dl> <p><a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">foo</span> <span class="o">=</span> <span class="p">{}</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">dict</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="p">{</span><span class="s1">'newkey'</span><span class="p">:</span> <span class="s1">'newvalue'</span><span class="p">}):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="p">{</span><span class="s1">'newkey'</span><span class="p">:</span> <span class="s1">'newvalue'</span><span class="p">}</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="p">{}</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">os</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">dict</span><span class="p">(</span><span class="s1">'os.environ'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'newkey'</span><span class="p">:</span> <span class="s1">'newvalue'</span><span class="p">}):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">'newkey'</span><span class="p">])</span> <span class="gp">...</span> <span class="go">newvalue</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="s1">'newkey'</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span> </pre></div> </div> <p>Keywords can be used in the <a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> call to set values in the dictionary:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mymodule</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mymodule</span><span class="o">.</span><span class="n">function</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'fish'</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">dict</span><span class="p">(</span><span class="s1">'sys.modules'</span><span class="p">,</span> <span class="n">mymodule</span><span class="o">=</span><span class="n">mymodule</span><span class="p">):</span> <span class="gp">... </span> <span class="kn">import</span> <span class="nn">mymodule</span> <span class="gp">... </span> <span class="n">mymodule</span><span class="o">.</span><span class="n">function</span><span class="p">(</span><span class="s1">'some'</span><span class="p">,</span> <span class="s1">'args'</span><span class="p">)</span> <span class="gp">...</span> <span class="go">'fish'</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> can be used with dictionary like objects that aren’t actually dictionaries. At the very minimum they must support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a> and either <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Container</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="p">{}</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span> <span class="gp">... </span> <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">thing</span> <span class="o">=</span> <span class="n">Container</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">thing</span><span class="p">[</span><span class="s1">'one'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">dict</span><span class="p">(</span><span class="n">thing</span><span class="p">,</span> <span class="n">one</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">two</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">thing</span><span class="p">[</span><span class="s1">'one'</span><span class="p">]</span> <span class="o">==</span> <span class="mi">2</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">thing</span><span class="p">[</span><span class="s1">'two'</span><span class="p">]</span> <span class="o">==</span> <span class="mi">3</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">thing</span><span class="p">[</span><span class="s1">'one'</span><span class="p">]</span> <span class="o">==</span> <span class="mi">1</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="nb">list</span><span class="p">(</span><span class="n">thing</span><span class="p">)</span> <span class="o">==</span> <span class="p">[</span><span class="s1">'one'</span><span class="p">]</span> </pre></div> </div> </div> <div class="section" id="patch-multiple"> <h3>patch.multiple<a class="headerlink" href="#patch-multiple" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.patch.multiple"> <code class="descclassname">patch.</code><code class="descname">multiple</code><span class="sig-paren">(</span><em>target</em>, <em>spec=None</em>, <em>create=False</em>, <em>spec_set=None</em>, <em>autospec=None</em>, <em>new_callable=None</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.patch.multiple" title="Permalink to this definition">¶</a></dt> <dd><p>Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">multiple</span><span class="p">(</span><span class="n">settings</span><span class="p">,</span> <span class="n">FIRST_PATCH</span><span class="o">=</span><span class="s1">'one'</span><span class="p">,</span> <span class="n">SECOND_PATCH</span><span class="o">=</span><span class="s1">'two'</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>Use <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a> as the value if you want <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> is used as a context manager.</p> <p><a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> can be used as a decorator, class decorator or a context manager. The arguments <em>spec</em>, <em>spec_set</em>, <em>create</em>, <em>autospec</em> and <em>new_callable</em> have the same meaning as for <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>. These arguments will be applied to <em>all</em> patches done by <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a>.</p> <p>When used as a class decorator <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> honours <code class="docutils literal notranslate"><span class="pre">patch.TEST_PREFIX</span></code> for choosing which methods to wrap.</p> </dd></dl> <p>If you want <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> to create mocks for you, then you can use <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a> as the value. If you use <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> as a decorator then the created mocks are passed into the decorated function by keyword.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">thing</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">other</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="o">.</span><span class="n">multiple</span><span class="p">(</span><span class="s1">'__main__'</span><span class="p">,</span> <span class="n">thing</span><span class="o">=</span><span class="n">DEFAULT</span><span class="p">,</span> <span class="n">other</span><span class="o">=</span><span class="n">DEFAULT</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test_function</span><span class="p">(</span><span class="n">thing</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">thing</span><span class="p">,</span> <span class="n">MagicMock</span><span class="p">)</span> <span class="gp">... </span> <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">MagicMock</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test_function</span><span class="p">()</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> can be nested with other <code class="docutils literal notranslate"><span class="pre">patch</span></code> decorators, but put arguments passed by keyword <em>after</em> any of the standard arguments created by <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'sys.exit'</span><span class="p">)</span> <span class="gp">... </span><span class="nd">@patch</span><span class="o">.</span><span class="n">multiple</span><span class="p">(</span><span class="s1">'__main__'</span><span class="p">,</span> <span class="n">thing</span><span class="o">=</span><span class="n">DEFAULT</span><span class="p">,</span> <span class="n">other</span><span class="o">=</span><span class="n">DEFAULT</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test_function</span><span class="p">(</span><span class="n">mock_exit</span><span class="p">,</span> <span class="n">other</span><span class="p">,</span> <span class="n">thing</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="s1">'other'</span> <span class="ow">in</span> <span class="nb">repr</span><span class="p">(</span><span class="n">other</span><span class="p">)</span> <span class="gp">... </span> <span class="k">assert</span> <span class="s1">'thing'</span> <span class="ow">in</span> <span class="nb">repr</span><span class="p">(</span><span class="n">thing</span><span class="p">)</span> <span class="gp">... </span> <span class="k">assert</span> <span class="s1">'exit'</span> <span class="ow">in</span> <span class="nb">repr</span><span class="p">(</span><span class="n">mock_exit</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test_function</span><span class="p">()</span> </pre></div> </div> <p>If <a class="reference internal" href="#unittest.mock.patch.multiple" title="unittest.mock.patch.multiple"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.multiple()</span></code></a> is used as a context manager, the value returned by the context manager is a dictionary where created mocks are keyed by name:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="o">.</span><span class="n">multiple</span><span class="p">(</span><span class="s1">'__main__'</span><span class="p">,</span> <span class="n">thing</span><span class="o">=</span><span class="n">DEFAULT</span><span class="p">,</span> <span class="n">other</span><span class="o">=</span><span class="n">DEFAULT</span><span class="p">)</span> <span class="k">as</span> <span class="n">values</span><span class="p">:</span> <span class="gp">... </span> <span class="k">assert</span> <span class="s1">'other'</span> <span class="ow">in</span> <span class="nb">repr</span><span class="p">(</span><span class="n">values</span><span class="p">[</span><span class="s1">'other'</span><span class="p">])</span> <span class="gp">... </span> <span class="k">assert</span> <span class="s1">'thing'</span> <span class="ow">in</span> <span class="nb">repr</span><span class="p">(</span><span class="n">values</span><span class="p">[</span><span class="s1">'thing'</span><span class="p">])</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">values</span><span class="p">[</span><span class="s1">'thing'</span><span class="p">]</span> <span class="ow">is</span> <span class="n">thing</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">values</span><span class="p">[</span><span class="s1">'other'</span><span class="p">]</span> <span class="ow">is</span> <span class="n">other</span> <span class="gp">...</span> </pre></div> </div> </div> <div class="section" id="patch-methods-start-and-stop"> <span id="start-and-stop"></span><h3>patch methods: start and stop<a class="headerlink" href="#patch-methods-start-and-stop" title="Permalink to this headline">¶</a></h3> <p>All the patchers have <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code> methods. These make it simpler to do patching in <code class="docutils literal notranslate"><span class="pre">setUp</span></code> methods or where you want to do multiple patches without nesting decorators or with statements.</p> <p>To use them call <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>, <a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> or <a class="reference internal" href="#unittest.mock.patch.dict" title="unittest.mock.patch.dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.dict()</span></code></a> as normal and keep a reference to the returned <code class="docutils literal notranslate"><span class="pre">patcher</span></code> object. You can then call <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> to put the patch in place and <code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code> to undo it.</p> <p>If you are using <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> to create a mock for you then it will be returned by the call to <code class="docutils literal notranslate"><span class="pre">patcher.start</span></code>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'package.module.ClassName'</span><span class="p">)</span> <span class="gp">>>> </span><span class="kn">from</span> <span class="nn">package</span> <span class="k">import</span> <span class="n">module</span> <span class="gp">>>> </span><span class="n">original</span> <span class="o">=</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName</span> <span class="gp">>>> </span><span class="n">new_mock</span> <span class="o">=</span> <span class="n">patcher</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">original</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName</span> <span class="ow">is</span> <span class="n">new_mock</span> <span class="gp">>>> </span><span class="n">patcher</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName</span> <span class="ow">is</span> <span class="n">original</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">module</span><span class="o">.</span><span class="n">ClassName</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">new_mock</span> </pre></div> </div> <p>A typical use case for this might be for doing multiple patches in the <code class="docutils literal notranslate"><span class="pre">setUp</span></code> method of a <code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">MyTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">patcher1</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'package.module.Class1'</span><span class="p">)</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">patcher2</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'package.module.Class2'</span><span class="p">)</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">MockClass1</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">patcher1</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">MockClass2</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">patcher2</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">tearDown</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">patcher1</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">patcher2</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">package</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">Class1</span> <span class="ow">is</span> <span class="bp">self</span><span class="o">.</span><span class="n">MockClass1</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">package</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">Class2</span> <span class="ow">is</span> <span class="bp">self</span><span class="o">.</span><span class="n">MockClass2</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_something'</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> </pre></div> </div> <div class="admonition caution"> <p class="admonition-title">Caution</p> <p>If you use this technique you must ensure that the patching is “undone” by calling <code class="docutils literal notranslate"><span class="pre">stop</span></code>. This can be fiddlier than you might think, because if an exception is raised in the <code class="docutils literal notranslate"><span class="pre">setUp</span></code> then <code class="docutils literal notranslate"><span class="pre">tearDown</span></code> is not called. <a class="reference internal" href="unittest.html#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unittest.TestCase.addCleanup()</span></code></a> makes this easier:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">MyTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'package.module.Class'</span><span class="p">)</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">MockClass</span> <span class="o">=</span> <span class="n">patcher</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">addCleanup</span><span class="p">(</span><span class="n">patcher</span><span class="o">.</span><span class="n">stop</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">test_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">package</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">Class</span> <span class="ow">is</span> <span class="bp">self</span><span class="o">.</span><span class="n">MockClass</span> <span class="gp">...</span> </pre></div> </div> <p>As an added bonus you no longer need to keep a reference to the <code class="docutils literal notranslate"><span class="pre">patcher</span></code> object.</p> </div> <p>It is also possible to stop all patches which have been started by using <a class="reference internal" href="#unittest.mock.patch.stopall" title="unittest.mock.patch.stopall"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.stopall()</span></code></a>.</p> <dl class="function"> <dt id="unittest.mock.patch.stopall"> <code class="descclassname">patch.</code><code class="descname">stopall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.patch.stopall" title="Permalink to this definition">¶</a></dt> <dd><p>Stop all active patches. Only stops patches started with <code class="docutils literal notranslate"><span class="pre">start</span></code>.</p> </dd></dl> </div> <div class="section" id="patch-builtins"> <span id="id4"></span><h3>patch builtins<a class="headerlink" href="#patch-builtins" title="Permalink to this headline">¶</a></h3> <p>You can patch any builtins within a module. The following example patches builtin <a class="reference internal" href="functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'__main__.ord'</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">mock_ord</span><span class="p">):</span> <span class="gp">... </span> <span class="n">mock_ord</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="mi">101</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">ord</span><span class="p">(</span><span class="s1">'c'</span><span class="p">))</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> <span class="go">101</span> </pre></div> </div> </div> <div class="section" id="test-prefix"> <h3>TEST_PREFIX<a class="headerlink" href="#test-prefix" title="Permalink to this headline">¶</a></h3> <p>All of the patchers can be used as class decorators. When used in this way they wrap every test method on the class. The patchers recognise methods that start with <code class="docutils literal notranslate"><span class="pre">'test'</span></code> as being test methods. This is the same way that the <a class="reference internal" href="unittest.html#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestLoader</span></code></a> finds test methods by default.</p> <p>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 <code class="docutils literal notranslate"><span class="pre">patch.TEST_PREFIX</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">patch</span><span class="o">.</span><span class="n">TEST_PREFIX</span> <span class="o">=</span> <span class="s1">'foo'</span> <span class="gp">>>> </span><span class="n">value</span> <span class="o">=</span> <span class="mi">3</span> <span class="go">>>></span> <span class="gp">>>> </span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'__main__.value'</span><span class="p">,</span> <span class="s1">'not three'</span><span class="p">)</span> <span class="gp">... </span><span class="k">class</span> <span class="nc">Thing</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">foo_one</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">foo_two</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="gp">...</span> <span class="go">>>></span> <span class="gp">>>> </span><span class="n">Thing</span><span class="p">()</span><span class="o">.</span><span class="n">foo_one</span><span class="p">()</span> <span class="go">not three</span> <span class="gp">>>> </span><span class="n">Thing</span><span class="p">()</span><span class="o">.</span><span class="n">foo_two</span><span class="p">()</span> <span class="go">not three</span> <span class="gp">>>> </span><span class="n">value</span> <span class="go">3</span> </pre></div> </div> </div> <div class="section" id="nesting-patch-decorators"> <h3>Nesting Patch Decorators<a class="headerlink" href="#nesting-patch-decorators" title="Permalink to this headline">¶</a></h3> <p>If you want to perform multiple patches then you can simply stack up the decorators.</p> <p>You can stack up multiple patch decorators using this pattern:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nd">@patch</span><span class="o">.</span><span class="n">object</span><span class="p">(</span><span class="n">SomeClass</span><span class="p">,</span> <span class="s1">'class_method'</span><span class="p">)</span> <span class="gp">... </span><span class="nd">@patch</span><span class="o">.</span><span class="n">object</span><span class="p">(</span><span class="n">SomeClass</span><span class="p">,</span> <span class="s1">'static_method'</span><span class="p">)</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">mock1</span><span class="p">,</span> <span class="n">mock2</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">SomeClass</span><span class="o">.</span><span class="n">static_method</span> <span class="ow">is</span> <span class="n">mock1</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">SomeClass</span><span class="o">.</span><span class="n">class_method</span> <span class="ow">is</span> <span class="n">mock2</span> <span class="gp">... </span> <span class="n">SomeClass</span><span class="o">.</span><span class="n">static_method</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">SomeClass</span><span class="o">.</span><span class="n">class_method</span><span class="p">(</span><span class="s1">'bar'</span><span class="p">)</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">mock1</span><span class="p">,</span> <span class="n">mock2</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock1</span><span class="p">,</span> <span class="n">mock2</span> <span class="o">=</span> <span class="n">test</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock1</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock2</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'bar'</span><span class="p">)</span> </pre></div> </div> <p>Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.</p> </div> <div class="section" id="where-to-patch"> <span id="id5"></span><h3>Where to patch<a class="headerlink" href="#where-to-patch" title="Permalink to this headline">¶</a></h3> <p><a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> works by (temporarily) changing the object that a <em>name</em> points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.</p> <p>The basic principle is that you patch where an object is <em>looked up</em>, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.</p> <p>Imagine we have a project that we want to test with the following structure:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span><span class="o">.</span><span class="n">py</span> <span class="o">-></span> <span class="n">Defines</span> <span class="n">SomeClass</span> <span class="n">b</span><span class="o">.</span><span class="n">py</span> <span class="o">-></span> <span class="kn">from</span> <span class="nn">a</span> <span class="k">import</span> <span class="n">SomeClass</span> <span class="o">-></span> <span class="n">some_function</span> <span class="n">instantiates</span> <span class="n">SomeClass</span> </pre></div> </div> <p>Now we want to test <code class="docutils literal notranslate"><span class="pre">some_function</span></code> but we want to mock out <code class="docutils literal notranslate"><span class="pre">SomeClass</span></code> using <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>. The problem is that when we import module b, which we will have to do then it imports <code class="docutils literal notranslate"><span class="pre">SomeClass</span></code> from module a. If we use <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> to mock out <code class="docutils literal notranslate"><span class="pre">a.SomeClass</span></code> then it will have no effect on our test; module b already has a reference to the <em>real</em> <code class="docutils literal notranslate"><span class="pre">SomeClass</span></code> and it looks like our patching had no effect.</p> <p>The key is to patch out <code class="docutils literal notranslate"><span class="pre">SomeClass</span></code> where it is used (or where it is looked up). In this case <code class="docutils literal notranslate"><span class="pre">some_function</span></code> will actually look up <code class="docutils literal notranslate"><span class="pre">SomeClass</span></code> in module b, where we have imported it. The patching should look like:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'b.SomeClass'</span><span class="p">)</span> </pre></div> </div> <p>However, consider the alternative scenario where instead of <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">a</span> <span class="pre">import</span> <span class="pre">SomeClass</span></code> module b does <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">some_function</span></code> uses <code class="docutils literal notranslate"><span class="pre">a.SomeClass</span></code>. Both of these import forms are common. In this case the class we want to patch is being looked up in the module and so we have to patch <code class="docutils literal notranslate"><span class="pre">a.SomeClass</span></code> instead:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@patch</span><span class="p">(</span><span class="s1">'a.SomeClass'</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="patching-descriptors-and-proxy-objects"> <h3>Patching Descriptors and Proxy Objects<a class="headerlink" href="#patching-descriptors-and-proxy-objects" title="Permalink to this headline">¶</a></h3> <p>Both <a class="reference internal" href="#patch">patch</a> and <a class="reference internal" href="#patch-object">patch.object</a> correctly patch and restore descriptors: class methods, static methods and properties. You should patch these on the <em>class</em> rather than an instance. They also work with <em>some</em> objects that proxy attribute access, like the <a class="reference external" href="http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198">django settings object</a>.</p> </div> </div> <div class="section" id="magicmock-and-magic-method-support"> <h2>MagicMock and magic method support<a class="headerlink" href="#magicmock-and-magic-method-support" title="Permalink to this headline">¶</a></h2> <div class="section" id="mocking-magic-methods"> <span id="magic-methods"></span><h3>Mocking Magic Methods<a class="headerlink" href="#mocking-magic-methods" title="Permalink to this headline">¶</a></h3> <p><a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> supports mocking the Python protocol methods, also known as “magic methods”. This allows mock objects to replace containers or other objects that implement Python protocols.</p> <p>Because magic methods are looked up differently from normal methods <a class="footnote-reference brackets" href="#id8" id="id6">2</a>, this support has been specially implemented. This means that only specific magic methods are supported. The supported list includes <em>almost</em> all of them. If there are any missing that you need please let us know.</p> <p>You mock magic methods by setting the method you are interested in to a function or a mock instance. If you are using a function then it <em>must</em> take <code class="docutils literal notranslate"><span class="pre">self</span></code> as the first argument <a class="footnote-reference brackets" href="#id9" id="id7">3</a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="s1">'fooble'</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__str__</span> <span class="o">=</span> <span class="fm">__str__</span> <span class="gp">>>> </span><span class="nb">str</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">'fooble'</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__str__</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__str__</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'fooble'</span> <span class="gp">>>> </span><span class="nb">str</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">'fooble'</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__iter__</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="nb">iter</span><span class="p">([]))</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">[]</span> </pre></div> </div> <p>One use case for this is for mocking objects used as context managers in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__enter__</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="s1">'foo'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__exit__</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">mock</span> <span class="k">as</span> <span class="n">m</span><span class="p">:</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">m</span> <span class="o">==</span> <span class="s1">'foo'</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__enter__</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__exit__</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> </pre></div> </div> <p>Calls to magic methods do not appear in <a class="reference internal" href="#unittest.mock.Mock.method_calls" title="unittest.mock.Mock.method_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method_calls</span></code></a>, but they are recorded in <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If you use the <em>spec</em> keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p> </div> <p>The full list of supported magic methods is:</p> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">__hash__</span></code>, <code class="docutils literal notranslate"><span class="pre">__sizeof__</span></code>, <code class="docutils literal notranslate"><span class="pre">__repr__</span></code> and <code class="docutils literal notranslate"><span class="pre">__str__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__dir__</span></code>, <code class="docutils literal notranslate"><span class="pre">__format__</span></code> and <code class="docutils literal notranslate"><span class="pre">__subclasses__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__floor__</span></code>, <code class="docutils literal notranslate"><span class="pre">__trunc__</span></code> and <code class="docutils literal notranslate"><span class="pre">__ceil__</span></code></p></li> <li><p>Comparisons: <code class="docutils literal notranslate"><span class="pre">__lt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__gt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__le__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ge__</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code> and <code class="docutils literal notranslate"><span class="pre">__ne__</span></code></p></li> <li><p>Container methods: <code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>, <code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__len__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__reversed__</span></code> and <code class="docutils literal notranslate"><span class="pre">__missing__</span></code></p></li> <li><p>Context manager: <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> and <code class="docutils literal notranslate"><span class="pre">__exit__</span></code></p></li> <li><p>Unary numeric methods: <code class="docutils literal notranslate"><span class="pre">__neg__</span></code>, <code class="docutils literal notranslate"><span class="pre">__pos__</span></code> and <code class="docutils literal notranslate"><span class="pre">__invert__</span></code></p></li> <li><p>The numeric methods (including right hand and in-place variants): <code class="docutils literal notranslate"><span class="pre">__add__</span></code>, <code class="docutils literal notranslate"><span class="pre">__sub__</span></code>, <code class="docutils literal notranslate"><span class="pre">__mul__</span></code>, <code class="docutils literal notranslate"><span class="pre">__matmul__</span></code>, <code class="docutils literal notranslate"><span class="pre">__div__</span></code>, <code class="docutils literal notranslate"><span class="pre">__truediv__</span></code>, <code class="docutils literal notranslate"><span class="pre">__floordiv__</span></code>, <code class="docutils literal notranslate"><span class="pre">__mod__</span></code>, <code class="docutils literal notranslate"><span class="pre">__divmod__</span></code>, <code class="docutils literal notranslate"><span class="pre">__lshift__</span></code>, <code class="docutils literal notranslate"><span class="pre">__rshift__</span></code>, <code class="docutils literal notranslate"><span class="pre">__and__</span></code>, <code class="docutils literal notranslate"><span class="pre">__xor__</span></code>, <code class="docutils literal notranslate"><span class="pre">__or__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__pow__</span></code></p></li> <li><p>Numeric conversion methods: <code class="docutils literal notranslate"><span class="pre">__complex__</span></code>, <code class="docutils literal notranslate"><span class="pre">__int__</span></code>, <code class="docutils literal notranslate"><span class="pre">__float__</span></code> and <code class="docutils literal notranslate"><span class="pre">__index__</span></code></p></li> <li><p>Descriptor methods: <code class="docutils literal notranslate"><span class="pre">__get__</span></code>, <code class="docutils literal notranslate"><span class="pre">__set__</span></code> and <code class="docutils literal notranslate"><span class="pre">__delete__</span></code></p></li> <li><p>Pickling: <code class="docutils literal notranslate"><span class="pre">__reduce__</span></code>, <code class="docutils literal notranslate"><span class="pre">__reduce_ex__</span></code>, <code class="docutils literal notranslate"><span class="pre">__getinitargs__</span></code>, <code class="docutils literal notranslate"><span class="pre">__getnewargs__</span></code>, <code class="docutils literal notranslate"><span class="pre">__getstate__</span></code> and <code class="docutils literal notranslate"><span class="pre">__setstate__</span></code></p></li> </ul> <p>The following methods exist but are <em>not</em> supported as they are either in use by mock, can’t be set dynamically, or can cause problems:</p> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">__getattr__</span></code>, <code class="docutils literal notranslate"><span class="pre">__setattr__</span></code>, <code class="docutils literal notranslate"><span class="pre">__init__</span></code> and <code class="docutils literal notranslate"><span class="pre">__new__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__prepare__</span></code>, <code class="docutils literal notranslate"><span class="pre">__instancecheck__</span></code>, <code class="docutils literal notranslate"><span class="pre">__subclasscheck__</span></code>, <code class="docutils literal notranslate"><span class="pre">__del__</span></code></p></li> </ul> </div> <div class="section" id="magic-mock"> <h3>Magic Mock<a class="headerlink" href="#magic-mock" title="Permalink to this headline">¶</a></h3> <p>There are two <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> variants: <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> and <a class="reference internal" href="#unittest.mock.NonCallableMagicMock" title="unittest.mock.NonCallableMagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">NonCallableMagicMock</span></code></a>.</p> <dl class="class"> <dt id="unittest.mock.MagicMock"> <em class="property">class </em><code class="descclassname">unittest.mock.</code><code class="descname">MagicMock</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.MagicMock" title="Permalink to this definition">¶</a></dt> <dd><p><code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> is a subclass of <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> with default implementations of most of the magic methods. You can use <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> without having to configure the magic methods yourself.</p> <p>The constructor parameters have the same meaning as for <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>.</p> <p>If you use the <em>spec</em> or <em>spec_set</em> arguments then <em>only</em> magic methods that exist in the spec will be created.</p> </dd></dl> <dl class="class"> <dt id="unittest.mock.NonCallableMagicMock"> <em class="property">class </em><code class="descclassname">unittest.mock.</code><code class="descname">NonCallableMagicMock</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.NonCallableMagicMock" title="Permalink to this definition">¶</a></dt> <dd><p>A non-callable version of <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a>.</p> <p>The constructor parameters have the same meaning as for <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a>, with the exception of <em>return_value</em> and <em>side_effect</em> which have no meaning on a non-callable mock.</p> </dd></dl> <p>The magic methods are setup with <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> objects, so you can configure them and use them in the usual way:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'fish'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__setitem__</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">'fish'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__getitem__</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="s1">'result'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="go">'result'</span> </pre></div> </div> <p>By default many of the protocol methods are required to return objects of a specific type. These methods are preconfigured with a default return value, so that they can be used without you having to do anything if you aren’t interested in the return value. You can still <em>set</em> the return value manually if you want to change the default.</p> <p>Methods and their defaults:</p> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">__lt__</span></code>: NotImplemented</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__gt__</span></code>: NotImplemented</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__le__</span></code>: NotImplemented</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__ge__</span></code>: NotImplemented</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__int__</span></code>: 1</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>: False</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__len__</span></code>: 0</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__iter__</span></code>: iter([])</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__exit__</span></code>: False</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__complex__</span></code>: 1j</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__float__</span></code>: 1.0</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__bool__</span></code>: True</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__index__</span></code>: 1</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__hash__</span></code>: default hash for the mock</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__str__</span></code>: default str for the mock</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__sizeof__</span></code>: default sizeof for the mock</p></li> </ul> <p>For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="nb">int</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">1</span> <span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">0</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">[]</span> <span class="gp">>>> </span><span class="nb">object</span><span class="p">()</span> <span class="ow">in</span> <span class="n">mock</span> <span class="go">False</span> </pre></div> </div> <p>The two equality methods, <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a>, are special. They do the default equality comparison on identity, using the <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> attribute, unless you change their return value to return something else:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">MagicMock</span><span class="p">()</span> <span class="o">==</span> <span class="mi">3</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">MagicMock</span><span class="p">()</span> <span class="o">!=</span> <span class="mi">3</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__eq__</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="kc">True</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">==</span> <span class="mi">3</span> <span class="go">True</span> </pre></div> </div> <p>The return value of <code class="xref py py-meth docutils literal notranslate"><span class="pre">MagicMock.__iter__()</span></code> can be any iterable object and isn’t required to be an iterator:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__iter__</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">]</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">['a', 'b', 'c']</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">['a', 'b', 'c']</span> </pre></div> </div> <p>If the return value <em>is</em> an iterator, then iterating over it once will consume it and subsequent iterations will result in an empty list:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="fm">__iter__</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">([</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">])</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">['a', 'b', 'c']</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="go">[]</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> has all of the supported magic methods configured except for some of the obscure and obsolete ones. You can still set these up if you want.</p> <p>Magic methods that are supported but not setup by default in <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> are:</p> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">__subclasses__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__dir__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__format__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__get__</span></code>, <code class="docutils literal notranslate"><span class="pre">__set__</span></code> and <code class="docutils literal notranslate"><span class="pre">__delete__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__reversed__</span></code> and <code class="docutils literal notranslate"><span class="pre">__missing__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__reduce__</span></code>, <code class="docutils literal notranslate"><span class="pre">__reduce_ex__</span></code>, <code class="docutils literal notranslate"><span class="pre">__getinitargs__</span></code>, <code class="docutils literal notranslate"><span class="pre">__getnewargs__</span></code>, <code class="docutils literal notranslate"><span class="pre">__getstate__</span></code> and <code class="docutils literal notranslate"><span class="pre">__setstate__</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">__getformat__</span></code> and <code class="docutils literal notranslate"><span class="pre">__setformat__</span></code></p></li> </ul> <dl class="footnote brackets"> <dt class="label" id="id8"><span class="brackets"><a class="fn-backref" href="#id6">2</a></span></dt> <dd><p>Magic methods <em>should</em> be looked up on the class rather than the instance. Different versions of Python are inconsistent about applying this rule. The supported protocol methods should work with all supported versions of Python.</p> </dd> <dt class="label" id="id9"><span class="brackets"><a class="fn-backref" href="#id7">3</a></span></dt> <dd><p>The function is basically hooked up to the class, but each <code class="docutils literal notranslate"><span class="pre">Mock</span></code> instance is kept isolated from the others.</p> </dd> </dl> </div> </div> <div class="section" id="helpers"> <h2>Helpers<a class="headerlink" href="#helpers" title="Permalink to this headline">¶</a></h2> <div class="section" id="sentinel"> <h3>sentinel<a class="headerlink" href="#sentinel" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="unittest.mock.sentinel"> <code class="descclassname">unittest.mock.</code><code class="descname">sentinel</code><a class="headerlink" href="#unittest.mock.sentinel" title="Permalink to this definition">¶</a></dt> <dd><p>The <code class="docutils literal notranslate"><span class="pre">sentinel</span></code> object provides a convenient way of providing unique objects for your tests.</p> <p>Attributes are created on demand when you access them by name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <code class="docutils literal notranslate"><span class="pre">sentinel</span></code> attributes now preserve their identity when they are <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copied</span></code></a> or <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickled</span></code></a>.</p> </div> </dd></dl> <p>Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. <a class="reference internal" href="#unittest.mock.sentinel" title="unittest.mock.sentinel"><code class="xref py py-data docutils literal notranslate"><span class="pre">sentinel</span></code></a> provides a convenient way of creating and testing the identity of objects like this.</p> <p>In this example we monkey patch <code class="docutils literal notranslate"><span class="pre">method</span></code> to return <code class="docutils literal notranslate"><span class="pre">sentinel.some_object</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">real</span> <span class="o">=</span> <span class="n">ProductionClass</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">real</span><span class="o">.</span><span class="n">method</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">"method"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">real</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">some_object</span> <span class="gp">>>> </span><span class="n">result</span> <span class="o">=</span> <span class="n">real</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">result</span> <span class="ow">is</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">some_object</span> <span class="gp">>>> </span><span class="n">sentinel</span><span class="o">.</span><span class="n">some_object</span> <span class="go">sentinel.some_object</span> </pre></div> </div> </div> <div class="section" id="default"> <h3>DEFAULT<a class="headerlink" href="#default" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="unittest.mock.DEFAULT"> <code class="descclassname">unittest.mock.</code><code class="descname">DEFAULT</code><a class="headerlink" href="#unittest.mock.DEFAULT" title="Permalink to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="#unittest.mock.DEFAULT" title="unittest.mock.DEFAULT"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT</span></code></a> object is a pre-created sentinel (actually <code class="docutils literal notranslate"><span class="pre">sentinel.DEFAULT</span></code>). It can be used by <a class="reference internal" href="#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code></a> functions to indicate that the normal return value should be used.</p> </dd></dl> </div> <div class="section" id="call"> <h3>call<a class="headerlink" href="#call" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.call"> <code class="descclassname">unittest.mock.</code><code class="descname">call</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.call" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-func docutils literal notranslate"><span class="pre">call()</span></code></a> is a helper object for making simpler assertions, for comparing with <a class="reference internal" href="#unittest.mock.Mock.call_args" title="unittest.mock.Mock.call_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args</span></code></a>, <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args_list</span></code></a>, <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.method_calls" title="unittest.mock.Mock.method_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method_calls</span></code></a>. <a class="reference internal" href="#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-func docutils literal notranslate"><span class="pre">call()</span></code></a> can also be used with <a class="reference internal" href="#unittest.mock.Mock.assert_has_calls" title="unittest.mock.Mock.assert_has_calls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_has_calls()</span></code></a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="s1">'foo'</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="s1">'bar'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">call_args_list</span> <span class="o">==</span> <span class="p">[</span><span class="n">call</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="s1">'foo'</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="s1">'bar'</span><span class="p">),</span> <span class="n">call</span><span class="p">()]</span> <span class="go">True</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="unittest.mock.call.call_list"> <code class="descclassname">call.</code><code class="descname">call_list</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.call.call_list" title="Permalink to this definition">¶</a></dt> <dd><p>For a call object that represents multiple calls, <a class="reference internal" href="#unittest.mock.call.call_list" title="unittest.mock.call.call_list"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_list()</span></code></a> returns a list of all the intermediate calls as well as the final call.</p> </dd></dl> <p><code class="docutils literal notranslate"><span class="pre">call_list</span></code> is particularly useful for making assertions on “chained calls”. A chained call is multiple calls on a single line of code. This results in multiple entries in <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a> on a mock. Manually constructing the sequence of calls can be tedious.</p> <p><a class="reference internal" href="#unittest.mock.call.call_list" title="unittest.mock.call.call_list"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_list()</span></code></a> can construct the sequence of calls from the same chained call:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="n">arg</span><span class="o">=</span><span class="s1">'foo'</span><span class="p">)</span><span class="o">.</span><span class="n">other</span><span class="p">(</span><span class="s1">'bar'</span><span class="p">)(</span><span class="mf">2.0</span><span class="p">)</span> <span class="go"><MagicMock name='mock().method().other()()' id='...'></span> <span class="gp">>>> </span><span class="n">kall</span> <span class="o">=</span> <span class="n">call</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="n">arg</span><span class="o">=</span><span class="s1">'foo'</span><span class="p">)</span><span class="o">.</span><span class="n">other</span><span class="p">(</span><span class="s1">'bar'</span><span class="p">)(</span><span class="mf">2.0</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">kall</span><span class="o">.</span><span class="n">call_list</span><span class="p">()</span> <span class="go">[call(1),</span> <span class="go"> call().method(arg='foo'),</span> <span class="go"> call().method().other('bar'),</span> <span class="go"> call().method().other()(2.0)]</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span> <span class="o">==</span> <span class="n">kall</span><span class="o">.</span><span class="n">call_list</span><span class="p">()</span> <span class="go">True</span> </pre></div> </div> <p id="calls-as-tuples">A <code class="docutils literal notranslate"><span class="pre">call</span></code> object is either a tuple of (positional args, keyword args) or (name, positional args, keyword args) depending on how it was constructed. When you construct them yourself this isn’t particularly interesting, but the <code class="docutils literal notranslate"><span class="pre">call</span></code> objects that are in the <a class="reference internal" href="#unittest.mock.Mock.call_args" title="unittest.mock.Mock.call_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Mock.call_args</span></code></a>, <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Mock.call_args_list</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Mock.mock_calls</span></code></a> attributes can be introspected to get at the individual arguments they contain.</p> <p>The <code class="docutils literal notranslate"><span class="pre">call</span></code> objects in <a class="reference internal" href="#unittest.mock.Mock.call_args" title="unittest.mock.Mock.call_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Mock.call_args</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Mock.call_args_list</span></code></a> are two-tuples of (positional args, keyword args) whereas the <code class="docutils literal notranslate"><span class="pre">call</span></code> objects in <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Mock.mock_calls</span></code></a>, along with ones you construct yourself, are three-tuples of (name, positional args, keyword args).</p> <p>You can use their “tupleness” to pull out the individual arguments for more complex introspection and assertions. The positional arguments are a tuple (an empty tuple if there are no positional arguments) and the keyword arguments are a dictionary:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="n">arg</span><span class="o">=</span><span class="s1">'one'</span><span class="p">,</span> <span class="n">arg2</span><span class="o">=</span><span class="s1">'two'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">kall</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">call_args</span> <span class="gp">>>> </span><span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">kall</span> <span class="gp">>>> </span><span class="n">args</span> <span class="go">(1, 2, 3)</span> <span class="gp">>>> </span><span class="n">kwargs</span> <span class="go">{'arg2': 'two', 'arg': 'one'}</span> <span class="gp">>>> </span><span class="n">args</span> <span class="ow">is</span> <span class="n">kall</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">kwargs</span> <span class="ow">is</span> <span class="n">kall</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="go">True</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">foo</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="n">arg</span><span class="o">=</span><span class="s1">'two'</span><span class="p">,</span> <span class="n">arg2</span><span class="o">=</span><span class="s1">'three'</span><span class="p">)</span> <span class="go"><MagicMock name='mock.foo()' id='...'></span> <span class="gp">>>> </span><span class="n">kall</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">name</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">kall</span> <span class="gp">>>> </span><span class="n">name</span> <span class="go">'foo'</span> <span class="gp">>>> </span><span class="n">args</span> <span class="go">(4, 5, 6)</span> <span class="gp">>>> </span><span class="n">kwargs</span> <span class="go">{'arg2': 'three', 'arg': 'two'}</span> <span class="gp">>>> </span><span class="n">name</span> <span class="ow">is</span> <span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="go">True</span> </pre></div> </div> </div> <div class="section" id="create-autospec"> <h3>create_autospec<a class="headerlink" href="#create-autospec" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.create_autospec"> <code class="descclassname">unittest.mock.</code><code class="descname">create_autospec</code><span class="sig-paren">(</span><em>spec</em>, <em>spec_set=False</em>, <em>instance=False</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.create_autospec" title="Permalink to this definition">¶</a></dt> <dd><p>Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the <em>spec</em> object as their spec.</p> <p>Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.</p> <p>If <em>spec_set</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> then attempting to set attributes that don’t exist on the spec object will raise an <a class="reference internal" href="exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p> <p>If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing <code class="docutils literal notranslate"><span class="pre">instance=True</span></code>. The returned mock will only be callable if instances of the mock are callable.</p> <p><a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> also takes arbitrary keyword arguments that are passed to the constructor of the created mock.</p> </dd></dl> <p>See <a class="reference internal" href="#auto-speccing"><span class="std std-ref">Autospeccing</span></a> for examples of how to use auto-speccing with <a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> and the <em>autospec</em> argument to <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a>.</p> </div> <div class="section" id="any"> <h3>ANY<a class="headerlink" href="#any" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="unittest.mock.ANY"> <code class="descclassname">unittest.mock.</code><code class="descname">ANY</code><a class="headerlink" href="#unittest.mock.ANY" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Sometimes you may need to make assertions about <em>some</em> of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of <a class="reference internal" href="#unittest.mock.Mock.call_args" title="unittest.mock.Mock.call_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">call_args</span></code></a> and make more complex assertions on them.</p> <p>To ignore certain arguments you can pass in objects that compare equal to <em>everything</em>. Calls to <a class="reference internal" href="#unittest.mock.Mock.assert_called_with" title="unittest.mock.Mock.assert_called_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_with()</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.assert_called_once_with" title="unittest.mock.Mock.assert_called_once_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_once_with()</span></code></a> will then succeed no matter what was passed in.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="nb">object</span><span class="p">())</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="n">ANY</span><span class="p">)</span> </pre></div> </div> <p><a class="reference internal" href="#unittest.mock.ANY" title="unittest.mock.ANY"><code class="xref py py-data docutils literal notranslate"><span class="pre">ANY</span></code></a> can also be used in comparisons with call lists like <a class="reference internal" href="#unittest.mock.Mock.mock_calls" title="unittest.mock.Mock.mock_calls"><code class="xref py py-attr docutils literal notranslate"><span class="pre">mock_calls</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">(</span><span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="nb">object</span><span class="p">())</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span> <span class="o">==</span> <span class="p">[</span><span class="n">call</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">call</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="n">ANY</span><span class="p">]</span> <span class="go">True</span> </pre></div> </div> </div> <div class="section" id="filter-dir"> <h3>FILTER_DIR<a class="headerlink" href="#filter-dir" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="unittest.mock.FILTER_DIR"> <code class="descclassname">unittest.mock.</code><code class="descname">FILTER_DIR</code><a class="headerlink" href="#unittest.mock.FILTER_DIR" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><a class="reference internal" href="#unittest.mock.FILTER_DIR" title="unittest.mock.FILTER_DIR"><code class="xref py py-data docutils literal notranslate"><span class="pre">FILTER_DIR</span></code></a> is a module level variable that controls the way mock objects respond to <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> (only for Python 2.6 or more recent). The default is <code class="docutils literal notranslate"><span class="pre">True</span></code>, which uses the filtering described below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set <code class="docutils literal notranslate"><span class="pre">mock.FILTER_DIR</span> <span class="pre">=</span> <span class="pre">False</span></code>.</p> <p>With filtering on, <code class="docutils literal notranslate"><span class="pre">dir(some_mock)</span></code> shows only useful attributes and will include any dynamically created attributes that wouldn’t normally be shown. If the mock was created with a <em>spec</em> (or <em>autospec</em> of course) then all the attributes from the original are shown, even if they haven’t been accessed yet:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">Mock</span><span class="p">())</span> <span class="go">['assert_any_call',</span> <span class="go"> 'assert_called_once_with',</span> <span class="go"> 'assert_called_with',</span> <span class="go"> 'assert_has_calls',</span> <span class="go"> 'attach_mock',</span> <span class="go"> ...</span> <span class="gp">>>> </span><span class="kn">from</span> <span class="nn">urllib</span> <span class="k">import</span> <span class="n">request</span> <span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">Mock</span><span class="p">(</span><span class="n">spec</span><span class="o">=</span><span class="n">request</span><span class="p">))</span> <span class="go">['AbstractBasicAuthHandler',</span> <span class="go"> 'AbstractDigestAuthHandler',</span> <span class="go"> 'AbstractHTTPHandler',</span> <span class="go"> 'BaseHandler',</span> <span class="go"> ...</span> </pre></div> </div> <p>Many of the not-very-useful (private to <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> rather than the thing being mocked) underscore and double underscore prefixed attributes have been filtered from the result of calling <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> on a <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>. If you dislike this behaviour you can switch it off by setting the module level switch <a class="reference internal" href="#unittest.mock.FILTER_DIR" title="unittest.mock.FILTER_DIR"><code class="xref py py-data docutils literal notranslate"><span class="pre">FILTER_DIR</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">unittest</span> <span class="k">import</span> <span class="n">mock</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">FILTER_DIR</span> <span class="o">=</span> <span class="kc">False</span> <span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">mock</span><span class="o">.</span><span class="n">Mock</span><span class="p">())</span> <span class="go">['_NonCallableMock__get_return_value',</span> <span class="go"> '_NonCallableMock__get_side_effect',</span> <span class="go"> '_NonCallableMock__return_value_doc',</span> <span class="go"> '_NonCallableMock__set_return_value',</span> <span class="go"> '_NonCallableMock__set_side_effect',</span> <span class="go"> '__call__',</span> <span class="go"> '__class__',</span> <span class="go"> ...</span> </pre></div> </div> <p>Alternatively you can just use <code class="docutils literal notranslate"><span class="pre">vars(my_mock)</span></code> (instance members) and <code class="docutils literal notranslate"><span class="pre">dir(type(my_mock))</span></code> (type members) to bypass the filtering irrespective of <code class="xref py py-data docutils literal notranslate"><span class="pre">mock.FILTER_DIR</span></code>.</p> </div> <div class="section" id="mock-open"> <h3>mock_open<a class="headerlink" href="#mock-open" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.mock_open"> <code class="descclassname">unittest.mock.</code><code class="descname">mock_open</code><span class="sig-paren">(</span><em>mock=None</em>, <em>read_data=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.mock_open" title="Permalink to this definition">¶</a></dt> <dd><p>A helper function to create a mock to replace the use of <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>. It works for <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> called directly or used as a context manager.</p> <p>The <em>mock</em> argument is the mock object to configure. If <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) then a <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> will be created for you, with the API limited to methods or attributes available on standard file handles.</p> <p><em>read_data</em> is a string for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>, <a class="reference internal" href="io.html#io.IOBase.readline" title="io.IOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, and <a class="reference internal" href="io.html#io.IOBase.readlines" title="io.IOBase.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a> methods of the file handle to return. Calls to those methods will take data from <em>read_data</em> until it is depleted. The mock of these methods is pretty simplistic: every time the <em>mock</em> is called, the <em>read_data</em> is rewound to the start. If you need more control over the data that you are feeding to the tested code you will need to customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on <a class="reference external" href="https://pypi.org">PyPI</a> can offer a realistic filesystem for testing.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>Added <a class="reference internal" href="io.html#io.IOBase.readline" title="io.IOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> and <a class="reference internal" href="io.html#io.IOBase.readlines" title="io.IOBase.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a> support. The mock of <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> changed to consume <em>read_data</em> rather than returning it on each call.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><em>read_data</em> is now reset on each call to the <em>mock</em>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7.1: </span>Added <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> to implementation so that iteration (such as in for loops) correctly consumes <em>read_data</em>.</p> </div> </dd></dl> <p>Using <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> as a context manager is a great way to ensure your file handles are closed properly and is becoming common:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'/some/path'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span> <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">'something'</span><span class="p">)</span> </pre></div> </div> <p>The issue is that even if you mock out the call to <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> it is the <em>returned object</em> that is used as a context manager (and has <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> called).</p> <p>Mocking context managers with a <a class="reference internal" href="#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> is common enough and fiddly enough that a helper function is useful.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">mock_open</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.open'</span><span class="p">,</span> <span class="n">m</span><span class="p">):</span> <span class="gp">... </span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">h</span><span class="p">:</span> <span class="gp">... </span> <span class="n">h</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">'some stuff'</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call('foo', 'w'),</span> <span class="go"> call().__enter__(),</span> <span class="go"> call().write('some stuff'),</span> <span class="go"> call().__exit__(None, None, None)]</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">handle</span> <span class="o">=</span> <span class="n">m</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">handle</span><span class="o">.</span><span class="n">write</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'some stuff'</span><span class="p">)</span> </pre></div> </div> <p>And for reading files:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.open'</span><span class="p">,</span> <span class="n">mock_open</span><span class="p">(</span><span class="n">read_data</span><span class="o">=</span><span class="s1">'bibble'</span><span class="p">))</span> <span class="k">as</span> <span class="n">m</span><span class="p">:</span> <span class="gp">... </span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">)</span> <span class="k">as</span> <span class="n">h</span><span class="p">:</span> <span class="gp">... </span> <span class="n">result</span> <span class="o">=</span> <span class="n">h</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">result</span> <span class="o">==</span> <span class="s1">'bibble'</span> </pre></div> </div> </div> <div class="section" id="autospeccing"> <span id="auto-speccing"></span><h3>Autospeccing<a class="headerlink" href="#autospeccing" title="Permalink to this headline">¶</a></h3> <p>Autospeccing is based on the existing <code class="xref py py-attr docutils literal notranslate"><span class="pre">spec</span></code> feature of mock. It limits the api of mocks to the api of an original object (the spec), but it is recursive (implemented lazily) so that attributes of mocks only have the same api as the attributes of the spec. In addition mocked functions / methods have the same call signature as the original so they raise a <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if they are called incorrectly.</p> <p>Before I explain how auto-speccing works, here’s why it is needed.</p> <p><a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> is a very powerful and flexible object, but it suffers from two flaws when used to mock out objects from a system under test. One of these flaws is specific to the <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> api and the other is a more general problem with using mock objects.</p> <p>First the problem specific to <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>. <a class="reference internal" href="#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> has two assert methods that are extremely handy: <a class="reference internal" href="#unittest.mock.Mock.assert_called_with" title="unittest.mock.Mock.assert_called_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_with()</span></code></a> and <a class="reference internal" href="#unittest.mock.Mock.assert_called_once_with" title="unittest.mock.Mock.assert_called_once_with"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_once_with()</span></code></a>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'Thing'</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected 'mock' to be called once. Called 2 times.</span> </pre></div> </div> <p>Because mocks auto-create attributes on demand, and allow you to call them with arbitrary arguments, if you misspell one of these assert methods then your assertion is gone:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'Thing'</span><span class="p">,</span> <span class="n">return_value</span><span class="o">=</span><span class="bp">None</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assret_called_once_with</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> </pre></div> </div> <p>Your tests can pass silently and incorrectly because of the typo.</p> <p>The second issue is more general to mocking. If you refactor some of your code, rename members and so on, any tests for code that is still using the <em>old api</em> but uses mocks instead of the real objects will still pass. This means your tests can all pass even though your code is broken.</p> <p>Note that this is another reason why you need integration tests as well as unit tests. Testing everything in isolation is all fine and dandy, but if you don’t test how your units are “wired together” there is still lots of room for bugs that tests might have caught.</p> <p><code class="xref py py-mod docutils literal notranslate"><span class="pre">mock</span></code> already provides a feature to help with this, called speccing. If you use a class or instance as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">spec</span></code> for a mock then you can only access attributes on the mock that exist on the real class:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">urllib</span> <span class="k">import</span> <span class="n">request</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">(</span><span class="n">spec</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">assret_called_with</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AttributeError</span>: <span class="n">Mock object has no attribute 'assret_called_with'</span> </pre></div> </div> <p>The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">has_data</span><span class="p">()</span> <span class="go"><mock.Mock object at 0x...></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">has_data</span><span class="o">.</span><span class="n">assret_called_with</span><span class="p">()</span> </pre></div> </div> <p>Auto-speccing solves this problem. You can either pass <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> to <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> / <a class="reference internal" href="#unittest.mock.patch.object" title="unittest.mock.patch.object"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch.object()</span></code></a> or use the <a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> function to create a mock with a spec. If you use the <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> argument to <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> then the object that is being replaced will be used as the spec object. Because the speccing is done “lazily” (the spec is created as attributes on the mock are accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.</p> <p>Here’s an example of it in use:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">urllib</span> <span class="k">import</span> <span class="n">request</span> <span class="gp">>>> </span><span class="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.request'</span><span class="p">,</span> <span class="n">autospec</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_request</span> <span class="o">=</span> <span class="n">patcher</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">request</span> <span class="ow">is</span> <span class="n">mock_request</span> <span class="go">True</span> <span class="gp">>>> </span><span class="n">mock_request</span><span class="o">.</span><span class="n">Request</span> <span class="go"><MagicMock name='request.Request' spec='Request' id='...'></span> </pre></div> </div> <p>You can see that <code class="xref py py-class docutils literal notranslate"><span class="pre">request.Request</span></code> has a spec. <code class="xref py py-class docutils literal notranslate"><span class="pre">request.Request</span></code> takes two arguments in the constructor (one of which is <em>self</em>). Here’s what happens if we try to call it incorrectly:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">req</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">()</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">TypeError</span>: <span class="n"><lambda>() takes at least 2 arguments (1 given)</span> </pre></div> </div> <p>The spec also applies to instantiated classes (i.e. the return value of specced mocks):</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">req</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">req</span> <span class="go"><NonCallableMagicMock name='request.Request()' spec='Request' id='...'></span> </pre></div> </div> <p><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code> objects are not callable, so the return value of instantiating our mocked out <code class="xref py py-class docutils literal notranslate"><span class="pre">request.Request</span></code> is a non-callable mock. With the spec in place any typos in our asserts will raise the correct error:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">)</span> <span class="go"><MagicMock name='request.Request().add_header()' id='...'></span> <span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="o">.</span><span class="n">assret_called_with</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AttributeError</span>: <span class="n">Mock object has no attribute 'assret_called_with'</span> <span class="gp">>>> </span><span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">)</span> </pre></div> </div> <p>In many cases you will just be able to add <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> to your existing <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> calls and then be protected against bugs due to typos and api changes.</p> <p>As well as using <em>autospec</em> through <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> there is a <a class="reference internal" href="#unittest.mock.create_autospec" title="unittest.mock.create_autospec"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_autospec()</span></code></a> for creating autospecced mocks directly:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">urllib</span> <span class="k">import</span> <span class="n">request</span> <span class="gp">>>> </span><span class="n">mock_request</span> <span class="o">=</span> <span class="n">create_autospec</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">'foo'</span><span class="p">,</span> <span class="s1">'bar'</span><span class="p">)</span> <span class="go"><NonCallableMagicMock name='mock.Request()' spec='Request' id='...'></span> </pre></div> </div> <p>This isn’t without caveats and limitations however, which is why it is not the default behaviour. In order to know what attributes are available on the spec object, autospec has to introspect (access attributes) the spec. As you traverse attributes on the mock a corresponding traversal of the original object is happening under the hood. If any of your specced objects have properties or descriptors that can trigger code execution then you may not be able to use autospec. On the other hand it is much better to design your objects so that introspection is safe <a class="footnote-reference brackets" href="#id11" id="id10">4</a>.</p> <p>A more serious problem is that it is common for instance attributes to be created in the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method and not to exist on the class at all. <em>autospec</em> can’t know about any dynamically created attributes and restricts the api to visible attributes.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Something</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">33</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Something'</span><span class="p">,</span> <span class="n">autospec</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="gp">... </span> <span class="n">thing</span> <span class="o">=</span> <span class="n">Something</span><span class="p">()</span> <span class="gp">... </span> <span class="n">thing</span><span class="o">.</span><span class="n">a</span> <span class="gp">...</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AttributeError</span>: <span class="n">Mock object has no attribute 'a'</span> </pre></div> </div> <p>There are a few different ways of resolving this problem. The easiest, but not necessarily the least annoying, way is to simply set the required attributes on the mock after creation. Just because <em>autospec</em> doesn’t allow you to fetch attributes that don’t exist on the spec it doesn’t prevent you setting them:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Something'</span><span class="p">,</span> <span class="n">autospec</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="gp">... </span> <span class="n">thing</span> <span class="o">=</span> <span class="n">Something</span><span class="p">()</span> <span class="gp">... </span> <span class="n">thing</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">33</span> <span class="gp">...</span> </pre></div> </div> <p>There is a more aggressive version of both <em>spec</em> and <em>autospec</em> that <em>does</em> prevent you setting non-existent attributes. This is useful if you want to ensure your code only <em>sets</em> valid attributes too, but obviously it prevents this particular scenario:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Something'</span><span class="p">,</span> <span class="n">autospec</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">spec_set</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="gp">... </span> <span class="n">thing</span> <span class="o">=</span> <span class="n">Something</span><span class="p">()</span> <span class="gp">... </span> <span class="n">thing</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">33</span> <span class="gp">...</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">AttributeError</span>: <span class="n">Mock object has no attribute 'a'</span> </pre></div> </div> <p>Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>. Note that if you are only setting default attributes in <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> then providing them via class attributes (shared between instances of course) is faster too. e.g.</p> <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Something</span><span class="p">:</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">33</span> </pre></div> </div> <p>This brings up another issue. It is relatively common to provide a default value of <code class="docutils literal notranslate"><span class="pre">None</span></code> for members that will later be an object of a different type. <code class="docutils literal notranslate"><span class="pre">None</span></code> would be useless as a spec because it wouldn’t let you access <em>any</em> attributes or methods on it. As <code class="docutils literal notranslate"><span class="pre">None</span></code> is <em>never</em> going to be useful as a spec, and probably indicates a member that will normally of some other type, autospec doesn’t use a spec for members that are set to <code class="docutils literal notranslate"><span class="pre">None</span></code>. These will just be ordinary mocks (well - MagicMocks):</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Something</span><span class="p">:</span> <span class="gp">... </span> <span class="n">member</span> <span class="o">=</span> <span class="kc">None</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">create_autospec</span><span class="p">(</span><span class="n">Something</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">member</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">bar</span><span class="o">.</span><span class="n">baz</span><span class="p">()</span> <span class="go"><MagicMock name='mock.member.foo.bar.baz()' id='...'></span> </pre></div> </div> <p>If modifying your production classes to add defaults isn’t to your liking then there are more options. One of these is simply to use an instance as the spec rather than the class. The other is to create a subclass of the 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 <a class="reference internal" href="#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> supports this - you can simply pass the alternative object as the <em>autospec</em> argument:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Something</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">33</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">class</span> <span class="nc">SomethingForTest</span><span class="p">(</span><span class="n">Something</span><span class="p">):</span> <span class="gp">... </span> <span class="n">a</span> <span class="o">=</span> <span class="mi">33</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'__main__.Something'</span><span class="p">,</span> <span class="n">autospec</span><span class="o">=</span><span class="n">SomethingForTest</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">a</span> <span class="go"><NonCallableMagicMock name='Something.a' spec='int' id='...'></span> </pre></div> </div> <dl class="footnote brackets"> <dt class="label" id="id11"><span class="brackets"><a class="fn-backref" href="#id10">4</a></span></dt> <dd><p>This only applies to classes or already instantiated objects. Calling a mocked class to create a mock instance <em>does not</em> create a real instance. It is only attribute lookups - along with calls to <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> - that are done.</p> </dd> </dl> </div> <div class="section" id="sealing-mocks"> <h3>Sealing mocks<a class="headerlink" href="#sealing-mocks" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="unittest.mock.seal"> <code class="descclassname">unittest.mock.</code><code class="descname">seal</code><span class="sig-paren">(</span><em>mock</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.mock.seal" title="Permalink to this definition">¶</a></dt> <dd><p>Seal will disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.</p> <p>If a mock instance with a name or a spec is assigned to an attribute it won’t be considered in the sealing chain. This allows one to prevent seal from fixing part of the mock object.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">submock</span><span class="o">.</span><span class="n">attribute1</span> <span class="o">=</span> <span class="mi">2</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">not_submock</span> <span class="o">=</span> <span class="n">mock</span><span class="o">.</span><span class="n">Mock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">"sample_name"</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">seal</span><span class="p">(</span><span class="n">mock</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">new_attribute</span> <span class="c1"># This will raise AttributeError.</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">submock</span><span class="o">.</span><span class="n">attribute2</span> <span class="c1"># This will raise AttributeError.</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">not_submock</span><span class="o">.</span><span class="n">attribute2</span> <span class="c1"># This won't raise.</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd></dl> </div> </div> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code> — mock object library</a><ul> <li><a class="reference internal" href="#quick-guide">Quick Guide</a></li> <li><a class="reference internal" href="#the-mock-class">The Mock Class</a><ul> <li><a class="reference internal" href="#calling">Calling</a></li> <li><a class="reference internal" href="#deleting-attributes">Deleting Attributes</a></li> <li><a class="reference internal" href="#mock-names-and-the-name-attribute">Mock names and the name attribute</a></li> <li><a class="reference internal" href="#attaching-mocks-as-attributes">Attaching Mocks as Attributes</a></li> </ul> </li> <li><a class="reference internal" href="#the-patchers">The patchers</a><ul> <li><a class="reference internal" href="#patch">patch</a></li> <li><a class="reference internal" href="#patch-object">patch.object</a></li> <li><a class="reference internal" href="#patch-dict">patch.dict</a></li> <li><a class="reference internal" href="#patch-multiple">patch.multiple</a></li> <li><a class="reference internal" href="#patch-methods-start-and-stop">patch methods: start and stop</a></li> <li><a class="reference internal" href="#patch-builtins">patch builtins</a></li> <li><a class="reference internal" href="#test-prefix">TEST_PREFIX</a></li> <li><a class="reference internal" href="#nesting-patch-decorators">Nesting Patch Decorators</a></li> <li><a class="reference internal" href="#where-to-patch">Where to patch</a></li> <li><a class="reference internal" href="#patching-descriptors-and-proxy-objects">Patching Descriptors and Proxy Objects</a></li> </ul> </li> <li><a class="reference internal" href="#magicmock-and-magic-method-support">MagicMock and magic method support</a><ul> <li><a class="reference internal" href="#mocking-magic-methods">Mocking Magic Methods</a></li> <li><a class="reference internal" href="#magic-mock">Magic Mock</a></li> </ul> </li> <li><a class="reference internal" href="#helpers">Helpers</a><ul> <li><a class="reference internal" href="#sentinel">sentinel</a></li> <li><a class="reference internal" href="#default">DEFAULT</a></li> <li><a class="reference internal" href="#call">call</a></li> <li><a class="reference internal" href="#create-autospec">create_autospec</a></li> <li><a class="reference internal" href="#any">ANY</a></li> <li><a class="reference internal" href="#filter-dir">FILTER_DIR</a></li> <li><a class="reference internal" href="#mock-open">mock_open</a></li> <li><a class="reference internal" href="#autospeccing">Autospeccing</a></li> <li><a class="reference internal" href="#sealing-mocks">Sealing mocks</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="unittest.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a></p> <h4>Next topic</h4> <p class="topless"><a href="unittest.mock-examples.html" title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code> — getting started</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li> <a href="https://github.com/python/cpython/blob/3.7/Doc/library/unittest.mock.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="unittest.mock-examples.html" title="unittest.mock — getting started" >next</a> |</li> <li class="right" > <a href="unittest.html" title="unittest — Unit testing framework" >previous</a> |</li> <li><img src="../_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li> <span class="language_switcher_placeholder">en</span> <span class="version_switcher_placeholder">3.7.4</span> <a href="../index.html">Documentation </a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li> <li class="nav-item nav-item-2"><a href="development.html" >Development Tools</a> »</li> <li class="right"> <div class="inline-search" style="display: none" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('.inline-search').show(0);</script> | </li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001-2019, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Jul 13, 2019. <a href="../bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1. </div> </body> </html>