<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>unittest.mock — getting started — 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="2to3 - Automated Python 2 to 3 code translation" href="2to3.html" /> <link rel="prev" title="unittest.mock — mock object library" href="unittest.mock.html" /> <link rel="shortcut icon" type="image/png" href="../_static/py.png" /> <link rel="canonical" href="https://docs.python.org/3/library/unittest.mock-examples.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="2to3.html" title="2to3 - Automated Python 2 to 3 code translation" accesskey="N">next</a> |</li> <li class="right" > <a href="unittest.mock.html" title="unittest.mock — mock object library" 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="unittest-mock-getting-started"> <h1><a class="reference internal" href="unittest.mock.html#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> — getting started<a class="headerlink" href="#unittest-mock-getting-started" title="Permalink to this headline">¶</a></h1> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="section" id="using-mock"> <span id="getting-started"></span><h2>Using Mock<a class="headerlink" href="#using-mock" title="Permalink to this headline">¶</a></h2> <div class="section" id="mock-patching-methods"> <h3>Mock Patching Methods<a class="headerlink" href="#mock-patching-methods" title="Permalink to this headline">¶</a></h3> <p>Common uses for <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> objects include:</p> <ul class="simple"> <li><p>Patching methods</p></li> <li><p>Recording method calls on objects</p></li> </ul> <p>You might want to replace a method on an object to check that it is called with the correct arguments by another part of the system:</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">SomeClass</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">MagicMock</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'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="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"><MagicMock name='method()' id='...'></span> </pre></div> </div> <p>Once our mock has been used (<code class="docutils literal notranslate"><span class="pre">real.method</span></code> in this example) it has methods and attributes that allow you to make assertions about how it has been used.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>In most of these examples the <a class="reference internal" href="unittest.mock.html#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.html#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> classes are interchangeable. As the <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> is the more capable class it makes a sensible one to use by default.</p> </div> <p>Once the mock has been called its <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock.called" title="unittest.mock.Mock.called"><code class="xref py py-attr docutils literal notranslate"><span class="pre">called</span></code></a> attribute is set to <code class="docutils literal notranslate"><span class="pre">True</span></code>. More importantly we can use the <a class="reference internal" href="unittest.mock.html#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> or <a class="reference internal" href="unittest.mock.html#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> method to check that it was called with the correct arguments.</p> <p>This example tests that calling <code class="docutils literal notranslate"><span class="pre">ProductionClass().method</span></code> results in a call to the <code class="docutils literal notranslate"><span class="pre">something</span></code> method:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">ProductionClass</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="bp">self</span><span class="o">.</span><span class="n">something</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="k">def</span> <span class="nf">something</span><span class="p">(</span><span class="bp">self</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">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">something</span> <span class="o">=</span> <span class="n">MagicMock</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="p">()</span> <span class="gp">>>> </span><span class="n">real</span><span class="o">.</span><span class="n">something</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> </div> <div class="section" id="mock-for-method-calls-on-an-object"> <h3>Mock for Method Calls on an Object<a class="headerlink" href="#mock-for-method-calls-on-an-object" title="Permalink to this headline">¶</a></h3> <p>In the last example we patched a method directly on an object to check that it was called correctly. Another common use case is to pass an object into a method (or some part of the system under test) and then check that it is used in the correct way.</p> <p>The simple <code class="docutils literal notranslate"><span class="pre">ProductionClass</span></code> below has a <code class="docutils literal notranslate"><span class="pre">closer</span></code> method. If it is called with an object then it calls <code class="docutils literal notranslate"><span class="pre">close</span></code> on it.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">ProductionClass</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">closer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">something</span><span class="p">):</span> <span class="gp">... </span> <span class="n">something</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="gp">...</span> </pre></div> </div> <p>So to test it we need to pass in an object with a <code class="docutils literal notranslate"><span class="pre">close</span></code> method and check that it was called correctly.</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">mock</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">real</span><span class="o">.</span><span class="n">closer</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">close</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">()</span> </pre></div> </div> <p>We don’t have to do any work to provide the ‘close’ method on our mock. Accessing close creates it. So, if ‘close’ hasn’t already been called then accessing it in the test will create it, but <a class="reference internal" href="unittest.mock.html#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> will raise a failure exception.</p> </div> <div class="section" id="mocking-classes"> <h3>Mocking Classes<a class="headerlink" href="#mocking-classes" title="Permalink to this headline">¶</a></h3> <p>A common use case is to mock out classes instantiated by your code under test. When you patch a class, then that class is replaced with a mock. Instances are created by <em>calling the class</em>. This means you access the “mock instance” by looking at the return value of the mocked class.</p> <p>In the example below we have a function <code class="docutils literal notranslate"><span class="pre">some_function</span></code> that instantiates <code class="docutils literal notranslate"><span class="pre">Foo</span></code> and calls a method on it. The call to <a class="reference internal" href="unittest.mock.html#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> replaces the class <code class="docutils literal notranslate"><span class="pre">Foo</span></code> with a mock. The <code class="docutils literal notranslate"><span class="pre">Foo</span></code> instance is the result of calling the mock, so it is configured by modifying the mock <a class="reference internal" href="unittest.mock.html#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> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">some_function</span><span class="p">():</span> <span class="gp">... </span> <span class="n">instance</span> <span class="o">=</span> <span class="n">module</span><span class="o">.</span><span class="n">Foo</span><span class="p">()</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">instance</span><span class="o">.</span><span class="n">method</span><span class="p">()</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">'module.Foo'</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock</span><span class="p">:</span> <span class="gp">... </span> <span class="n">instance</span> <span class="o">=</span> <span class="n">mock</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">'the result'</span> <span class="gp">... </span> <span class="n">result</span> <span class="o">=</span> <span class="n">some_function</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">'the result'</span> </pre></div> </div> </div> <div class="section" id="naming-your-mocks"> <h3>Naming your mocks<a class="headerlink" href="#naming-your-mocks" title="Permalink to this headline">¶</a></h3> <p>It can be useful to give your mocks a name. The name is shown in the repr of the mock and can be helpful when the mock appears in test failure messages. The name is also propagated to attributes or methods of 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">MagicMock</span><span class="p">(</span><span class="n">name</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="go"><MagicMock name='foo' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">method</span> <span class="go"><MagicMock name='foo.method' id='...'></span> </pre></div> </div> </div> <div class="section" id="tracking-all-calls"> <h3>Tracking all Calls<a class="headerlink" href="#tracking-all-calls" title="Permalink to this headline">¶</a></h3> <p>Often you want to track more than a single call to a method. The <a class="reference internal" href="unittest.mock.html#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> attribute records all calls to child attributes of the mock - and also to their children.</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">method</span><span class="p">()</span> <span class="go"><MagicMock name='mock.method()' id='...'></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">method</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">53</span><span class="p">)</span> <span class="go"><MagicMock name='mock.attribute.method()' 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.method(), call.attribute.method(10, x=53)]</span> </pre></div> </div> <p>If you make an assertion about <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code> and any unexpected methods have been called, then the assertion will fail. This is useful because as well as asserting that the calls you expected have been made, you are also checking that they were made in the right order and with no additional calls:</p> <p>You use the <a class="reference internal" href="unittest.mock.html#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> object to construct lists for comparing with <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></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="o">.</span><span class="n">method</span><span class="p">(),</span> <span class="n">call</span><span class="o">.</span><span class="n">attribute</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">53</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>However, parameters to calls that return mocks are not recorded, which means it is not possible to track nested calls where the parameters used to create ancestors are important:</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">factory</span><span class="p">(</span><span class="n">important</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span><span class="o">.</span><span class="n">deliver</span><span class="p">()</span> <span class="go"><Mock name='mock.factory().deliver()' id='...'></span> <span class="gp">>>> </span><span class="n">m</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">factory</span><span class="p">(</span><span class="n">important</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span><span class="o">.</span><span class="n">deliver</span><span class="p">()</span> <span class="go">True</span> </pre></div> </div> </div> <div class="section" id="setting-return-values-and-attributes"> <h3>Setting Return Values and Attributes<a class="headerlink" href="#setting-return-values-and-attributes" title="Permalink to this headline">¶</a></h3> <p>Setting the return values on a mock object is trivially easy:</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="mi">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="go">3</span> </pre></div> </div> <p>Of course you can do the same for methods on 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">method</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">mock</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="go">3</span> </pre></div> </div> <p>The return value 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="p">()</span> <span class="go">3</span> </pre></div> </div> <p>If you need an attribute setting on your mock, just do it:</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">x</span> <span class="o">=</span> <span class="mi">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">x</span> <span class="go">3</span> </pre></div> </div> <p>Sometimes you want to mock up a more complex situation, like for example <code class="docutils literal notranslate"><span class="pre">mock.connection.cursor().execute("SELECT</span> <span class="pre">1")</span></code>. If we wanted this call to return a list, then we have to configure the result of the nested call.</p> <p>We can use <a class="reference internal" href="unittest.mock.html#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> to construct the set of calls in a “chained call” like this for easy assertion afterwards:</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">cursor</span> <span class="o">=</span> <span class="n">mock</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="o">.</span><span class="n">return_value</span> <span class="gp">>>> </span><span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</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="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"SELECT 1"</span><span class="p">)</span> <span class="go">['foo']</span> <span class="gp">>>> </span><span class="n">expected</span> <span class="o">=</span> <span class="n">call</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">"SELECT 1"</span><span class="p">)</span><span class="o">.</span><span class="n">call_list</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="go">[call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]</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>It is the call to <code class="docutils literal notranslate"><span class="pre">.call_list()</span></code> that turns our call object into a list of calls representing the chained calls.</p> </div> <div class="section" id="raising-exceptions-with-mocks"> <h3>Raising exceptions with mocks<a class="headerlink" href="#raising-exceptions-with-mocks" title="Permalink to this headline">¶</a></h3> <p>A useful attribute is <a class="reference internal" href="unittest.mock.html#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>. If you set this to an exception class or instance then the exception will be raised when the 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">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> </div> <div class="section" id="side-effect-functions-and-iterables"> <h3>Side effect functions and iterables<a class="headerlink" href="#side-effect-functions-and-iterables" title="Permalink to this headline">¶</a></h3> <p><code class="docutils literal notranslate"><span class="pre">side_effect</span></code> can also be set to a function or an iterable. The use case for <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> as an iterable is where your mock is going to be called several times, and you want each call to return a different value. When you set <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> to an iterable every call to the mock returns the next value from the iterable:</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="n">side_effect</span><span class="o">=</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="gp">>>> </span><span class="n">mock</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="go">5</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">()</span> <span class="go">6</span> </pre></div> </div> <p>For more advanced use cases, like dynamically varying the return values depending on what the mock is called with, <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> can be a function. The function will be called with the same arguments as the mock. Whatever the function returns is what the call returns:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">vals</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">1</span><span class="p">,</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="mi">2</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="gp">... </span> <span class="k">return</span> <span class="n">vals</span><span class="p">[</span><span class="n">args</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">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">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="go">1</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="mi">3</span><span class="p">)</span> <span class="go">2</span> </pre></div> </div> </div> <div class="section" id="creating-a-mock-from-an-existing-object"> <h3>Creating a Mock from an Existing Object<a class="headerlink" href="#creating-a-mock-from-an-existing-object" title="Permalink to this headline">¶</a></h3> <p>One problem with over use of mocking is that it couples your tests to the implementation of your mocks rather than your real code. Suppose you have a class that implements <code class="docutils literal notranslate"><span class="pre">some_method</span></code>. In a test for another class, you provide a mock of this object that <em>also</em> provides <code class="docutils literal notranslate"><span class="pre">some_method</span></code>. If later you refactor the first class, so that it no longer has <code class="docutils literal notranslate"><span class="pre">some_method</span></code> - then your tests will continue to pass even though your code is now broken!</p> <p><a class="reference internal" href="unittest.mock.html#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> allows you to provide an object as a specification for the mock, using the <em>spec</em> keyword argument. Accessing methods / attributes on the mock that don’t exist on your specification object will immediately raise an attribute error. If you change the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those 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="n">mock</span><span class="o">.</span><span class="n">old_method</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">object has no attribute 'old_method'</span> </pre></div> </div> <p>Using a specification also enables a smarter matching of calls made to the mock, regardless of whether some parameters were passed as positional or named arguments:</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="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="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>If you want this smarter matching to also work with method calls on the mock, you can use <a class="reference internal" href="unittest.mock.html#auto-speccing"><span class="std std-ref">auto-speccing</span></a>.</p> <p>If you want a stronger form of specification that prevents the setting of arbitrary attributes as well as the getting of them then you can use <em>spec_set</em> instead of <em>spec</em>.</p> </div> </div> <div class="section" id="patch-decorators"> <h2>Patch Decorators<a class="headerlink" href="#patch-decorators" title="Permalink to this headline">¶</a></h2> <div class="admonition note"> <p class="admonition-title">Note</p> <p>With <a class="reference internal" href="unittest.mock.html#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="unittest.mock.html#where-to-patch"><span class="std std-ref">where to patch</span></a>.</p> </div> <p>A common need in tests is to patch a class attribute or a module attribute, for example patching a builtin or patching a class in a module to test that it is instantiated. Modules and classes are effectively global, so patching on them has to be undone after the test or the patch will persist into other tests and cause hard to diagnose problems.</p> <p>mock provides three convenient decorators for this: <a class="reference internal" href="unittest.mock.html#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.html#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> and <a class="reference internal" href="unittest.mock.html#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>. <code class="docutils literal notranslate"><span class="pre">patch</span></code> takes a single string, of the form <code class="docutils literal notranslate"><span class="pre">package.module.Class.attribute</span></code> to specify the attribute you are patching. It also optionally takes a value that you want the attribute (or class or whatever) to be replaced with. ‘patch.object’ takes an object and the name of the attribute you would like patched, plus optionally the value to patch it with.</p> <p><code class="docutils literal notranslate"><span class="pre">patch.object</span></code>:</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">SomeClass</span><span class="o">.</span><span class="n">attribute</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">'attribute'</span><span class="p">,</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">attribute</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">SomeClass</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="gp">>>> </span><span class="n">test</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">attribute</span> <span class="o">==</span> <span class="n">original</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="p">(</span><span class="s1">'package.module.attribute'</span><span class="p">,</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">attribute</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="kn">from</span> <span class="nn">package.module</span> <span class="k">import</span> <span class="n">attribute</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">attribute</span> <span class="ow">is</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">attribute</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">test</span><span class="p">()</span> </pre></div> </div> <p>If you are patching a module (including <a class="reference internal" href="builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>) then use <a class="reference internal" href="unittest.mock.html#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> instead of <a class="reference internal" href="unittest.mock.html#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>:</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="n">return_value</span><span class="o">=</span><span class="n">sentinel</span><span class="o">.</span><span class="n">file_handle</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">'builtins.open'</span><span class="p">,</span> <span class="n">mock</span><span class="p">):</span> <span class="gp">... </span> <span class="n">handle</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'filename'</span><span class="p">,</span> <span class="s1">'r'</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">assert_called_with</span><span class="p">(</span><span class="s1">'filename'</span><span class="p">,</span> <span class="s1">'r'</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">handle</span> <span class="o">==</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">file_handle</span><span class="p">,</span> <span class="s2">"incorrect file handle returned"</span> </pre></div> </div> <p>The module name can be ‘dotted’, in the form <code class="docutils literal notranslate"><span class="pre">package.module</span></code> if needed:</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">'package.module.ClassName.attribute'</span><span class="p">,</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">attribute</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="kn">from</span> <span class="nn">package.module</span> <span class="k">import</span> <span class="n">ClassName</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">ClassName</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="gp">>>> </span><span class="n">test</span><span class="p">()</span> </pre></div> </div> <p>A nice pattern is to actually decorate test methods themselves:</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">unittest</span><span class="o">.</span><span class="n">TestCase</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">'attribute'</span><span class="p">,</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">attribute</span><span class="p">)</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="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">SomeClass</span><span class="o">.</span><span class="n">attribute</span><span class="p">,</span> <span class="n">sentinel</span><span class="o">.</span><span class="n">attribute</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">original</span> <span class="o">=</span> <span class="n">SomeClass</span><span class="o">.</span><span class="n">attribute</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">test_something</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">attribute</span> <span class="o">==</span> <span class="n">original</span> </pre></div> </div> <p>If you want to patch with a Mock, you can use <a class="reference internal" href="unittest.mock.html#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> with only one argument (or <a class="reference internal" href="unittest.mock.html#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 two arguments). The mock will be created for you and passed into the test function / method:</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">unittest</span><span class="o">.</span><span class="n">TestCase</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_something</span><span class="p">(</span><span class="bp">self</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">static_method</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="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">test_something</span><span class="p">()</span> </pre></div> </div> <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="k">class</span> <span class="nc">MyTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span> <span class="gp">... </span> <span class="nd">@patch</span><span class="p">(</span><span class="s1">'package.module.ClassName1'</span><span class="p">)</span> <span class="gp">... </span> <span class="nd">@patch</span><span class="p">(</span><span class="s1">'package.module.ClassName2'</span><span class="p">)</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="n">MockClass2</span><span class="p">,</span> <span class="n">MockClass1</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">assertIs</span><span class="p">(</span><span class="n">package</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">ClassName1</span><span class="p">,</span> <span class="n">MockClass1</span><span class="p">)</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">assertIs</span><span class="p">(</span><span class="n">package</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">ClassName2</span><span class="p">,</span> <span class="n">MockClass2</span><span class="p">)</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">test_something</span><span class="p">()</span> </pre></div> </div> <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">test_module.ClassName2</span></code> is passed in first.</p> <p>There is also <a class="reference internal" href="unittest.mock.html#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><code class="docutils literal notranslate"><span class="pre">patch</span></code>, <code class="docutils literal notranslate"><span class="pre">patch.object</span></code> and <code class="docutils literal notranslate"><span class="pre">patch.dict</span></code> can all be used as context managers.</p> <p>Where you use <a class="reference internal" href="unittest.mock.html#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, you can get a reference to the mock using the “as” form of the with statement:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">ProductionClass</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="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="k">as</span> <span class="n">mock_method</span><span class="p">:</span> <span class="gp">... </span> <span class="n">mock_method</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="kc">None</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="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_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>As an alternative <code class="docutils literal notranslate"><span class="pre">patch</span></code>, <code class="docutils literal notranslate"><span class="pre">patch.object</span></code> and <code class="docutils literal notranslate"><span class="pre">patch.dict</span></code> can be used as class decorators. When used in this way it is the same as applying the decorator individually to every method whose name starts with “test”.</p> </div> <div class="section" id="further-examples"> <span id="id1"></span><h2>Further Examples<a class="headerlink" href="#further-examples" title="Permalink to this headline">¶</a></h2> <p>Here are some more examples for some slightly more advanced scenarios.</p> <div class="section" id="mocking-chained-calls"> <h3>Mocking chained calls<a class="headerlink" href="#mocking-chained-calls" title="Permalink to this headline">¶</a></h3> <p>Mocking chained calls is actually straightforward with mock once you understand the <a class="reference internal" href="unittest.mock.html#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. When a mock is called for the first time, or you fetch its <code class="docutils literal notranslate"><span class="pre">return_value</span></code> before it has been called, a new <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> is created.</p> <p>This means that you can see how the object returned from a call to a mocked object has been used by interrogating the <code class="docutils literal notranslate"><span class="pre">return_value</span></code> 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="p">()</span><span class="o">.</span><span class="n">foo</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="go"><Mock name='mock().foo()' 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">foo</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">2</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> </pre></div> </div> <p>From here it is a simple step to configure and then make assertions about chained calls. Of course another alternative is writing your code in a more testable way in the first place…</p> <p>So, suppose we have some code that looks a little bit like this:</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">backend</span> <span class="o">=</span> <span class="n">BackendProvider</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="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">backend</span><span class="o">.</span><span class="n">get_endpoint</span><span class="p">(</span><span class="s1">'foobar'</span><span class="p">)</span><span class="o">.</span><span class="n">create_call</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="o">.</span><span class="n">start_call</span><span class="p">()</span> <span class="gp">... </span> <span class="c1"># more code</span> </pre></div> </div> <p>Assuming that <code class="docutils literal notranslate"><span class="pre">BackendProvider</span></code> is already well tested, how do we test <code class="docutils literal notranslate"><span class="pre">method()</span></code>? Specifically, we want to test that the code section <code class="docutils literal notranslate"><span class="pre">#</span> <span class="pre">more</span> <span class="pre">code</span></code> uses the response object in the correct way.</p> <p>As this chain of calls is made from an instance attribute we can monkey patch the <code class="docutils literal notranslate"><span class="pre">backend</span></code> attribute on a <code class="docutils literal notranslate"><span class="pre">Something</span></code> instance. In this particular case we are only interested in the return value from the final call to <code class="docutils literal notranslate"><span class="pre">start_call</span></code> so we don’t have much configuration to do. Let’s assume the object it returns is ‘file-like’, so we’ll ensure that our response object uses the builtin <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 its <code class="docutils literal notranslate"><span class="pre">spec</span></code>.</p> <p>To do this we create a mock instance as our mock backend and create a mock response object for it. To set the response as the return value for that final <code class="docutils literal notranslate"><span class="pre">start_call</span></code> we could do this:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">mock_backend</span><span class="o">.</span><span class="n">get_endpoint</span><span class="o">.</span><span class="n">return_value</span><span class="o">.</span><span class="n">create_call</span><span class="o">.</span><span class="n">return_value</span><span class="o">.</span><span class="n">start_call</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="n">mock_response</span> </pre></div> </div> <p>We can do that in a slightly nicer way using the <a class="reference internal" href="unittest.mock.html#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 to directly set the return value for us:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">something</span> <span class="o">=</span> <span class="n">Something</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock_response</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="nb">open</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock_backend</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">config</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'get_endpoint.return_value.create_call.return_value.start_call.return_value'</span><span class="p">:</span> <span class="n">mock_response</span><span class="p">}</span> <span class="gp">>>> </span><span class="n">mock_backend</span><span class="o">.</span><span class="n">configure_mock</span><span class="p">(</span><span class="o">**</span><span class="n">config</span><span class="p">)</span> </pre></div> </div> <p>With these we monkey patch the “mock backend” in place and can make the real call:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">something</span><span class="o">.</span><span class="n">backend</span> <span class="o">=</span> <span class="n">mock_backend</span> <span class="gp">>>> </span><span class="n">something</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> </pre></div> </div> <p>Using <a class="reference internal" href="unittest.mock.html#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> we can check the chained call with a single assert. A chained call is several calls in one line of code, so there will be several entries in <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code>. We can use <a class="reference internal" href="unittest.mock.html#unittest.mock.call.call_list" title="unittest.mock.call.call_list"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call.call_list()</span></code></a> to create this list of calls for us:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">chained</span> <span class="o">=</span> <span class="n">call</span><span class="o">.</span><span class="n">get_endpoint</span><span class="p">(</span><span class="s1">'foobar'</span><span class="p">)</span><span class="o">.</span><span class="n">create_call</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="o">.</span><span class="n">start_call</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">call_list</span> <span class="o">=</span> <span class="n">chained</span><span class="o">.</span><span class="n">call_list</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">mock_backend</span><span class="o">.</span><span class="n">mock_calls</span> <span class="o">==</span> <span class="n">call_list</span> </pre></div> </div> </div> <div class="section" id="partial-mocking"> <h3>Partial mocking<a class="headerlink" href="#partial-mocking" title="Permalink to this headline">¶</a></h3> <p>In some tests I wanted to mock out a call to <a class="reference internal" href="datetime.html#datetime.date.today" title="datetime.date.today"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.date.today()</span></code></a> to return a known date, but I didn’t want to prevent the code under test from creating new date objects. Unfortunately <a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> is written in C, and so I couldn’t just monkey-patch out the static <code class="xref py py-meth docutils literal notranslate"><span class="pre">date.today()</span></code> method.</p> <p>I found a simple way of doing this that involved effectively wrapping the date class with a mock, but passing through calls to the constructor to the real class (and returning real instances).</p> <p>The <a class="reference internal" href="unittest.mock.html#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch</span> <span class="pre">decorator</span></code></a> is used here to mock out the <code class="docutils literal notranslate"><span class="pre">date</span></code> class in the module under test. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> attribute on the mock date class is then set to a lambda function that returns a real date. When the mock date class is called a real date will be constructed and returned by <code class="docutils literal notranslate"><span class="pre">side_effect</span></code>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">date</span> <span class="gp">>>> </span><span class="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'mymodule.date'</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_date</span><span class="p">:</span> <span class="gp">... </span> <span class="n">mock_date</span><span class="o">.</span><span class="n">today</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="gp">... </span> <span class="n">mock_date</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="k">lambda</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">:</span> <span class="n">date</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">kw</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span> <span class="o">==</span> <span class="n">date</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2009</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="o">==</span> <span class="n">date</span><span class="p">(</span><span class="mi">2009</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="gp">...</span> </pre></div> </div> <p>Note that we don’t patch <a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> globally, we patch <code class="docutils literal notranslate"><span class="pre">date</span></code> in the module that <em>uses</em> it. See <a class="reference internal" href="unittest.mock.html#where-to-patch"><span class="std std-ref">where to patch</span></a>.</p> <p>When <code class="docutils literal notranslate"><span class="pre">date.today()</span></code> is called a known date is returned, but calls to the <code class="docutils literal notranslate"><span class="pre">date(...)</span></code> constructor still return normal dates. Without this you can find yourself having to calculate an expected result using exactly the same algorithm as the code under test, which is a classic testing anti-pattern.</p> <p>Calls to the date constructor are recorded in the <code class="docutils literal notranslate"><span class="pre">mock_date</span></code> attributes (<code class="docutils literal notranslate"><span class="pre">call_count</span></code> and friends) which may also be useful for your tests.</p> <p>An alternative way of dealing with mocking dates, or other builtin classes, is discussed in <a class="reference external" href="https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/">this blog entry</a>.</p> </div> <div class="section" id="mocking-a-generator-method"> <h3>Mocking a Generator Method<a class="headerlink" href="#mocking-a-generator-method" title="Permalink to this headline">¶</a></h3> <p>A Python generator is a function or method that uses the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement to return a series of values when iterated over <a class="footnote-reference brackets" href="#id3" id="id2">1</a>.</p> <p>A generator method / function is called to return the generator object. It is the generator object that is then iterated over. The protocol method for iteration is <a class="reference internal" href="stdtypes.html#container.__iter__" title="container.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, so we can mock this using a <a class="reference internal" href="unittest.mock.html#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>Here’s an example class with an “iter” method implemented as a generator:</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="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">for</span> <span class="n">i</span> <span class="ow">in</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="k">yield</span> <span class="n">i</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">foo</span> <span class="o">=</span> <span class="n">Foo</span><span class="p">()</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">foo</span><span class="o">.</span><span class="n">iter</span><span class="p">())</span> <span class="go">[1, 2, 3]</span> </pre></div> </div> <p>How would we mock this class, and in particular its “iter” method?</p> <p>To configure the values returned from the iteration (implicit in the call to <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>), we need to configure the object returned by the call to <code class="docutils literal notranslate"><span class="pre">foo.iter()</span></code>.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock_foo</span> <span class="o">=</span> <span class="n">MagicMock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock_foo</span><span class="o">.</span><span class="n">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="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="nb">list</span><span class="p">(</span><span class="n">mock_foo</span><span class="o">.</span><span class="n">iter</span><span class="p">())</span> <span class="go">[1, 2, 3]</span> </pre></div> </div> <dl class="footnote brackets"> <dt class="label" id="id3"><span class="brackets"><a class="fn-backref" href="#id2">1</a></span></dt> <dd><p>There are also generator expressions and more <a class="reference external" href="http://www.dabeaz.com/coroutines/index.html">advanced uses</a> of generators, but we aren’t concerned about them here. A very good introduction to generators and how powerful they are is: <a class="reference external" href="http://www.dabeaz.com/generators/">Generator Tricks for Systems Programmers</a>.</p> </dd> </dl> </div> <div class="section" id="applying-the-same-patch-to-every-test-method"> <h3>Applying the same patch to every test method<a class="headerlink" href="#applying-the-same-patch-to-every-test-method" title="Permalink to this headline">¶</a></h3> <p>If you want several patches in place for multiple test methods the obvious way is to apply the patch decorators to every method. This can feel like unnecessary repetition. For Python 2.6 or more recent you can use <a class="reference internal" href="unittest.mock.html#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> (in all its various forms) as a class decorator. This applies the patches to all test methods on the class. A test method is identified by methods whose names start with <code class="docutils literal notranslate"><span class="pre">test</span></code>:</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">'mymodule.SomeClass'</span><span class="p">)</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="gp">... </span> <span class="k">def</span> <span class="nf">test_one</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">MockSomeClass</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">assertIs</span><span class="p">(</span><span class="n">mymodule</span><span class="o">.</span><span class="n">SomeClass</span><span class="p">,</span> <span class="n">MockSomeClass</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">test_two</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">MockSomeClass</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">assertIs</span><span class="p">(</span><span class="n">mymodule</span><span class="o">.</span><span class="n">SomeClass</span><span class="p">,</span> <span class="n">MockSomeClass</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">not_a_test</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="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_one'</span><span class="p">)</span><span class="o">.</span><span class="n">test_one</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_two'</span><span class="p">)</span><span class="o">.</span><span class="n">test_two</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_two'</span><span class="p">)</span><span class="o">.</span><span class="n">not_a_test</span><span class="p">()</span> <span class="go">'something'</span> </pre></div> </div> <p>An alternative way of managing patches is to use the <a class="reference internal" href="unittest.mock.html#start-and-stop"><span class="std std-ref">patch methods: start and stop</span></a>. These allow you to move the patching into your <code class="docutils literal notranslate"><span class="pre">setUp</span></code> and <code class="docutils literal notranslate"><span class="pre">tearDown</span></code> methods.</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">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'mymodule.foo'</span><span class="p">)</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">mock_foo</span> <span class="o">=</span> <span class="bp">self</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="gp">... </span> <span class="k">def</span> <span class="nf">test_foo</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">assertIs</span><span class="p">(</span><span class="n">mymodule</span><span class="o">.</span><span class="n">foo</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">mock_foo</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">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="n">MyTest</span><span class="p">(</span><span class="s1">'test_foo'</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> </pre></div> </div> <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 setUp then tearDown 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">'mymodule.foo'</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="bp">self</span><span class="o">.</span><span class="n">mock_foo</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="gp">... </span> <span class="k">def</span> <span class="nf">test_foo</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">assertIs</span><span class="p">(</span><span class="n">mymodule</span><span class="o">.</span><span class="n">foo</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">mock_foo</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_foo'</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> </pre></div> </div> </div> <div class="section" id="mocking-unbound-methods"> <h3>Mocking Unbound Methods<a class="headerlink" href="#mocking-unbound-methods" title="Permalink to this headline">¶</a></h3> <p>Whilst writing tests today I needed to patch an <em>unbound method</em> (patching the method on the class rather than on the instance). I needed self to be passed in as the first argument because I want to make asserts about which objects were calling this particular method. The issue is that you can’t patch with a mock for this, because if you replace an unbound method with a mock it doesn’t become a bound method when fetched from the instance, and so it doesn’t get self passed in. The workaround is to patch the unbound method with a real function instead. The <a class="reference internal" href="unittest.mock.html#unittest.mock.patch" title="unittest.mock.patch"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch()</span></code></a> decorator makes it so simple to patch out methods with a mock that having to create a real function becomes a nuisance.</p> <p>If you pass <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> to patch then it does the patching with a <em>real</em> function object. This function object has the same signature as the one it is replacing, but delegates to a mock under the hood. You still get your mock auto-created in exactly the same way as before. What it means though, is that if you use it to patch out an unbound method on a class the mocked function will be turned into a bound method if it is fetched from an instance. It will have <code class="docutils literal notranslate"><span class="pre">self</span></code> passed in as the first argument, which is exactly what I wanted:</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="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">pass</span> <span class="gp">...</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">Foo</span><span class="p">,</span> <span class="s1">'foo'</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="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">'foo'</span> <span class="gp">... </span> <span class="n">foo</span> <span class="o">=</span> <span class="n">Foo</span><span class="p">()</span> <span class="gp">... </span> <span class="n">foo</span><span class="o">.</span><span class="n">foo</span><span class="p">()</span> <span class="gp">...</span> <span class="go">'foo'</span> <span class="gp">>>> </span><span class="n">mock_foo</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="n">foo</span><span class="p">)</span> </pre></div> </div> <p>If we don’t use <code class="docutils literal notranslate"><span class="pre">autospec=True</span></code> then the unbound method is patched out with a Mock instance instead, and isn’t called with <code class="docutils literal notranslate"><span class="pre">self</span></code>.</p> </div> <div class="section" id="checking-multiple-calls-with-mock"> <h3>Checking multiple calls with mock<a class="headerlink" href="#checking-multiple-calls-with-mock" title="Permalink to this headline">¶</a></h3> <p>mock has a nice API for making assertions about how your mock objects are used.</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">foo_bar</span><span class="o">.</span><span class="n">return_value</span> <span class="o">=</span> <span class="kc">None</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">foo_bar</span><span class="p">(</span><span class="s1">'baz'</span><span class="p">,</span> <span class="n">spam</span><span class="o">=</span><span class="s1">'eggs'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">foo_bar</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="s1">'baz'</span><span class="p">,</span> <span class="n">spam</span><span class="o">=</span><span class="s1">'eggs'</span><span class="p">)</span> </pre></div> </div> <p>If your mock is only being called once you can use the <code class="xref py py-meth docutils literal notranslate"><span class="pre">assert_called_once_with()</span></code> method that also asserts that the <code class="xref py py-attr docutils literal notranslate"><span class="pre">call_count</span></code> is one.</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">foo_bar</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'baz'</span><span class="p">,</span> <span class="n">spam</span><span class="o">=</span><span class="s1">'eggs'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">foo_bar</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">foo_bar</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">(</span><span class="s1">'baz'</span><span class="p">,</span> <span class="n">spam</span><span class="o">=</span><span class="s1">'eggs'</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected to be called once. Called 2 times.</span> </pre></div> </div> <p>Both <code class="docutils literal notranslate"><span class="pre">assert_called_with</span></code> and <code class="docutils literal notranslate"><span class="pre">assert_called_once_with</span></code> make assertions about the <em>most recent</em> call. If your mock is going to be called several times, and you want to make assertions about <em>all</em> those calls you can use <a class="reference internal" href="unittest.mock.html#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="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">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="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_list</span> <span class="go">[call(1, 2, 3), call(4, 5, 6), call()]</span> </pre></div> </div> <p>The <a class="reference internal" href="unittest.mock.html#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> helper makes it easy to make assertions about these calls. You can build up a list of expected calls and compare it to <code class="docutils literal notranslate"><span class="pre">call_args_list</span></code>. This looks remarkably similar to the repr of the <code class="docutils literal notranslate"><span class="pre">call_args_list</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></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="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">call</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> </div> <div class="section" id="coping-with-mutable-arguments"> <h3>Coping with mutable arguments<a class="headerlink" href="#coping-with-mutable-arguments" title="Permalink to this headline">¶</a></h3> <p>Another situation is rare, but can bite you, is when your mock is called with mutable arguments. <code class="docutils literal notranslate"><span class="pre">call_args</span></code> and <code class="docutils literal notranslate"><span class="pre">call_args_list</span></code> store <em>references</em> to the arguments. If the arguments are mutated by the code under test then you can no longer make assertions about what the values were when the mock was called.</p> <p>Here’s some example code that shows the problem. Imagine the following functions defined in ‘mymodule’:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">frob</span><span class="p">(</span><span class="n">val</span><span class="p">):</span> <span class="k">pass</span> <span class="k">def</span> <span class="nf">grob</span><span class="p">(</span><span class="n">val</span><span class="p">):</span> <span class="s2">"First frob and then clear val"</span> <span class="n">frob</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="n">val</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span> </pre></div> </div> <p>When we try to test that <code class="docutils literal notranslate"><span class="pre">grob</span></code> calls <code class="docutils literal notranslate"><span class="pre">frob</span></code> with the correct argument look what happens:</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">'mymodule.frob'</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_frob</span><span class="p">:</span> <span class="gp">... </span> <span class="n">val</span> <span class="o">=</span> <span class="p">{</span><span class="mi">6</span><span class="p">}</span> <span class="gp">... </span> <span class="n">mymodule</span><span class="o">.</span><span class="n">grob</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">val</span> <span class="go">set()</span> <span class="gp">>>> </span><span class="n">mock_frob</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">({</span><span class="mi">6</span><span class="p">})</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected: (({6},), {})</span> <span class="go">Called with: ((set(),), {})</span> </pre></div> </div> <p>One possibility would be for mock to copy the arguments you pass in. This could then cause problems if you do assertions that rely on object identity for equality.</p> <p>Here’s one solution that uses the <code class="xref py py-attr docutils literal notranslate"><span class="pre">side_effect</span></code> functionality. If you provide a <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> function for a mock then <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> will be called with the same args as the mock. This gives us an opportunity to copy the arguments and store them for later assertions. In this example I’m using <em>another</em> mock to store the arguments so that I can use the mock methods for doing the assertion. Again a helper function sets this up for me.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">copy</span> <span class="k">import</span> <span class="n">deepcopy</span> <span class="gp">>>> </span><span class="kn">from</span> <span class="nn">unittest.mock</span> <span class="k">import</span> <span class="n">Mock</span><span class="p">,</span> <span class="n">patch</span><span class="p">,</span> <span class="n">DEFAULT</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">copy_call_args</span><span class="p">(</span><span class="n">mock</span><span class="p">):</span> <span class="gp">... </span> <span class="n">new_mock</span> <span class="o">=</span> <span class="n">Mock</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="n">args</span> <span class="o">=</span> <span class="n">deepcopy</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="gp">... </span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">deepcopy</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span> <span class="gp">... </span> <span class="n">new_mock</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="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="k">return</span> <span class="n">new_mock</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">'mymodule.frob'</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_frob</span><span class="p">:</span> <span class="gp">... </span> <span class="n">new_mock</span> <span class="o">=</span> <span class="n">copy_call_args</span><span class="p">(</span><span class="n">mock_frob</span><span class="p">)</span> <span class="gp">... </span> <span class="n">val</span> <span class="o">=</span> <span class="p">{</span><span class="mi">6</span><span class="p">}</span> <span class="gp">... </span> <span class="n">mymodule</span><span class="o">.</span><span class="n">grob</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">new_mock</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">({</span><span class="mi">6</span><span class="p">})</span> <span class="gp">>>> </span><span class="n">new_mock</span><span class="o">.</span><span class="n">call_args</span> <span class="go">call({6})</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">copy_call_args</span></code> is called with the mock that will be called. It returns a new mock that we do the assertion on. The <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> function makes a copy of the args and calls our <code class="docutils literal notranslate"><span class="pre">new_mock</span></code> with the copy.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If your mock is only going to be used once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> function.</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">arg</span><span class="p">):</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">arg</span> <span class="o">==</span> <span class="p">{</span><span class="mi">6</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">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">6</span><span class="p">})</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">(</span><span class="nb">set</span><span class="p">())</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AssertionError</span> </pre></div> </div> </div> <p>An alternative approach is to create a subclass of <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> or <a class="reference internal" href="unittest.mock.html#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a> that copies (using <a class="reference internal" href="copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a>) the arguments. Here’s an example implementation:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">copy</span> <span class="k">import</span> <span class="n">deepcopy</span> <span class="gp">>>> </span><span class="k">class</span> <span class="nc">CopyingMock</span><span class="p">(</span><span class="n">MagicMock</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</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="n">args</span> <span class="o">=</span> <span class="n">deepcopy</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="gp">... </span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">deepcopy</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span> <span class="gp">... </span> <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">CopyingMock</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__call__</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="gp">>>> </span><span class="n">c</span> <span class="o">=</span> <span class="n">CopyingMock</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">arg</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">c</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">arg</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="nb">set</span><span class="p">())</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected call: mock({1})</span> <span class="go">Actual call: mock(set())</span> <span class="gp">>>> </span><span class="n">c</span><span class="o">.</span><span class="n">foo</span> <span class="go"><CopyingMock name='mock.foo' id='...'></span> </pre></div> </div> <p>When you subclass <code class="docutils literal notranslate"><span class="pre">Mock</span></code> or <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> all dynamically created attributes, and the <code class="docutils literal notranslate"><span class="pre">return_value</span></code> will use your subclass automatically. That means all children of a <code class="docutils literal notranslate"><span class="pre">CopyingMock</span></code> will also have the type <code class="docutils literal notranslate"><span class="pre">CopyingMock</span></code>.</p> </div> <div class="section" id="nesting-patches"> <h3>Nesting Patches<a class="headerlink" href="#nesting-patches" title="Permalink to this headline">¶</a></h3> <p>Using patch as a context manager is nice, but if you do multiple patches you can end up with nested with statements indenting further and further to the right:</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="gp">... </span> <span class="k">def</span> <span class="nf">test_foo</span><span class="p">(</span><span class="bp">self</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">'mymodule.Foo'</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="k">with</span> <span class="n">patch</span><span class="p">(</span><span class="s1">'mymodule.Bar'</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_bar</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">'mymodule.Spam'</span><span class="p">)</span> <span class="k">as</span> <span class="n">mock_spam</span><span class="p">:</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Foo</span> <span class="ow">is</span> <span class="n">mock_foo</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Bar</span> <span class="ow">is</span> <span class="n">mock_bar</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Spam</span> <span class="ow">is</span> <span class="n">mock_spam</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">original</span> <span class="o">=</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Foo</span> <span class="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_foo'</span><span class="p">)</span><span class="o">.</span><span class="n">test_foo</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Foo</span> <span class="ow">is</span> <span class="n">original</span> </pre></div> </div> <p>With unittest <code class="docutils literal notranslate"><span class="pre">cleanup</span></code> functions and the <a class="reference internal" href="unittest.mock.html#start-and-stop"><span class="std std-ref">patch methods: start and stop</span></a> we can achieve the same effect without the nested indentation. A simple helper method, <code class="docutils literal notranslate"><span class="pre">create_patch</span></code>, puts the patch in place and returns the created mock for us:</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="gp">... </span> <span class="k">def</span> <span class="nf">create_patch</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="n">patcher</span> <span class="o">=</span> <span class="n">patch</span><span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="gp">... </span> <span class="n">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="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="k">return</span> <span class="n">thing</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">test_foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="n">mock_foo</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">create_patch</span><span class="p">(</span><span class="s1">'mymodule.Foo'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">mock_bar</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">create_patch</span><span class="p">(</span><span class="s1">'mymodule.Bar'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">mock_spam</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">create_patch</span><span class="p">(</span><span class="s1">'mymodule.Spam'</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Foo</span> <span class="ow">is</span> <span class="n">mock_foo</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Bar</span> <span class="ow">is</span> <span class="n">mock_bar</span> <span class="gp">... </span> <span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Spam</span> <span class="ow">is</span> <span class="n">mock_spam</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">original</span> <span class="o">=</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Foo</span> <span class="gp">>>> </span><span class="n">MyTest</span><span class="p">(</span><span class="s1">'test_foo'</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="n">mymodule</span><span class="o">.</span><span class="n">Foo</span> <span class="ow">is</span> <span class="n">original</span> </pre></div> </div> </div> <div class="section" id="mocking-a-dictionary-with-magicmock"> <h3>Mocking a dictionary with MagicMock<a class="headerlink" href="#mocking-a-dictionary-with-magicmock" title="Permalink to this headline">¶</a></h3> <p>You may want to mock a dictionary, or other container object, recording all access to it whilst having it still behave like a dictionary.</p> <p>We can do this with <a class="reference internal" href="unittest.mock.html#unittest.mock.MagicMock" title="unittest.mock.MagicMock"><code class="xref py py-class docutils literal notranslate"><span class="pre">MagicMock</span></code></a>, which will behave like a dictionary, and using <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock.side_effect" title="unittest.mock.Mock.side_effect"><code class="xref py py-data docutils literal notranslate"><span class="pre">side_effect</span></code></a> to delegate dictionary access to a real underlying dictionary that is under our control.</p> <p>When the <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> and <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> methods of our <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> are called (normal dictionary access) then <code class="docutils literal notranslate"><span class="pre">side_effect</span></code> is called with the key (and in the case of <code class="docutils literal notranslate"><span class="pre">__setitem__</span></code> the value too). We can also control what is returned.</p> <p>After the <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> has been used we can use attributes like <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock.call_args_list" title="unittest.mock.Mock.call_args_list"><code class="xref py py-data docutils literal notranslate"><span class="pre">call_args_list</span></code></a> to assert about how the dictionary was used:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">my_dict</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">getitem</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="n">my_dict</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="k">def</span> <span class="nf">setitem</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span> <span class="gp">... </span> <span class="n">my_dict</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">val</span> <span class="gp">...</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">__getitem__</span><span class="o">.</span><span class="n">side_effect</span> <span class="o">=</span> <span class="n">getitem</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">side_effect</span> <span class="o">=</span> <span class="n">setitem</span> </pre></div> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>An alternative to using <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> is to use <code class="docutils literal notranslate"><span class="pre">Mock</span></code> and <em>only</em> provide the magic methods you specifically want:</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">__getitem__</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">getitem</span><span class="p">)</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">Mock</span><span class="p">(</span><span class="n">side_effect</span><span class="o">=</span><span class="n">setitem</span><span class="p">)</span> </pre></div> </div> <p>A <em>third</em> option is to use <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> but passing in <code class="docutils literal notranslate"><span class="pre">dict</span></code> as the <em>spec</em> (or <em>spec_set</em>) argument so that the <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> created only has dictionary magic methods available:</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="n">spec_set</span><span class="o">=</span><span class="nb">dict</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">side_effect</span> <span class="o">=</span> <span class="n">getitem</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">side_effect</span> <span class="o">=</span> <span class="n">setitem</span> </pre></div> </div> </div> <p>With these side effect functions in place, the <code class="docutils literal notranslate"><span class="pre">mock</span></code> will behave like a normal dictionary but recording the access. It even raises a <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if you try to access a key that doesn’t exist.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></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="go">1</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="s1">'c'</span><span class="p">]</span> <span class="go">3</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="s1">'d'</span><span class="p">]</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">KeyError</span>: <span class="n">'d'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="s1">'b'</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="p">[</span><span class="s1">'d'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'eggs'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="s1">'b'</span><span class="p">]</span> <span class="go">'fish'</span> <span class="gp">>>> </span><span class="n">mock</span><span class="p">[</span><span class="s1">'d'</span><span class="p">]</span> <span class="go">'eggs'</span> </pre></div> </div> <p>After it has been used you can make assertions about the access using the normal mock 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="fm">__getitem__</span><span class="o">.</span><span class="n">call_args_list</span> <span class="go">[call('a'), call('c'), call('d'), call('b'), call('d')]</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">call_args_list</span> <span class="go">[call('b', 'fish'), call('d', 'eggs')]</span> <span class="gp">>>> </span><span class="n">my_dict</span> <span class="go">{'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}</span> </pre></div> </div> </div> <div class="section" id="mock-subclasses-and-their-attributes"> <h3>Mock subclasses and their attributes<a class="headerlink" href="#mock-subclasses-and-their-attributes" title="Permalink to this headline">¶</a></h3> <p>There are various reasons why you might want to subclass <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a>. One reason might be to add helper methods. Here’s a silly 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">MyMock</span><span class="p">(</span><span class="n">MagicMock</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">has_been_called</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="bp">self</span><span class="o">.</span><span class="n">called</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mymock</span> <span class="o">=</span> <span class="n">MyMock</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">mymock</span> <span class="go"><MyMock id='...'></span> <span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">has_been_called</span><span class="p">()</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">mymock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">has_been_called</span><span class="p">()</span> <span class="go">True</span> </pre></div> </div> <p>The standard behaviour for <code class="docutils literal notranslate"><span class="pre">Mock</span></code> instances is that attributes and the return value mocks are of the same type as the mock they are accessed on. This ensures that <code class="docutils literal notranslate"><span class="pre">Mock</span></code> attributes are <code class="docutils literal notranslate"><span class="pre">Mocks</span></code> and <code class="docutils literal notranslate"><span class="pre">MagicMock</span></code> attributes are <code class="docutils literal notranslate"><span class="pre">MagicMocks</span></code> <a class="footnote-reference brackets" href="#id5" id="id4">2</a>. So if you’re subclassing to add helper methods then they’ll also be available on the attributes and return value mock of instances of your subclass.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">foo</span> <span class="go"><MyMock name='mock.foo' id='...'></span> <span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">has_been_called</span><span class="p">()</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">foo</span><span class="p">()</span> <span class="go"><MyMock name='mock.foo()' id='...'></span> <span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">has_been_called</span><span class="p">()</span> <span class="go">True</span> </pre></div> </div> <p>Sometimes this is inconvenient. For example, <a class="reference external" href="https://code.google.com/archive/p/mock/issues/105">one user</a> is subclassing mock to created a <a class="reference external" href="https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html">Twisted adaptor</a>. Having this applied to attributes too actually causes errors.</p> <p><code class="docutils literal notranslate"><span class="pre">Mock</span></code> (in all its flavours) uses a method called <code class="docutils literal notranslate"><span class="pre">_get_child_mock</span></code> to create these “sub-mocks” for attributes and return values. You can prevent your subclass being used for attributes by overriding this method. The signature is that it takes arbitrary keyword arguments (<code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>) which are then passed onto the mock constructor:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Subclass</span><span class="p">(</span><span class="n">MagicMock</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">_get_child_mock</span><span class="p">(</span><span class="bp">self</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">MagicMock</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">mymock</span> <span class="o">=</span> <span class="n">Subclass</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mymock</span><span class="o">.</span><span class="n">foo</span> <span class="go"><MagicMock name='mock.foo' id='...'></span> <span class="gp">>>> </span><span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">mymock</span><span class="p">,</span> <span class="n">Subclass</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">mymock</span><span class="o">.</span><span class="n">foo</span><span class="p">,</span> <span class="n">Subclass</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">assert</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">mymock</span><span class="p">(),</span> <span class="n">Subclass</span><span class="p">)</span> </pre></div> </div> <dl class="footnote brackets"> <dt class="label" id="id5"><span class="brackets"><a class="fn-backref" href="#id4">2</a></span></dt> <dd><p>An exception to this rule are the non-callable mocks. Attributes use the callable variant because otherwise non-callable mocks couldn’t have callable methods.</p> </dd> </dl> </div> <div class="section" id="mocking-imports-with-patch-dict"> <h3>Mocking imports with patch.dict<a class="headerlink" href="#mocking-imports-with-patch-dict" title="Permalink to this headline">¶</a></h3> <p>One situation where mocking can be hard is where you have a local import inside a function. These are harder to mock because they aren’t using an object from the module namespace that we can patch out.</p> <p>Generally local imports are to be avoided. They are sometimes done to prevent circular dependencies, for which there is <em>usually</em> a much better way to solve the problem (refactor the code) or to prevent “up front costs” by delaying the import. This can also be solved in better ways than an unconditional local import (store the module as a class or module attribute and only do the import on first use).</p> <p>That aside there is a way to use <code class="docutils literal notranslate"><span class="pre">mock</span></code> to affect the results of an import. Importing fetches an <em>object</em> from the <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> dictionary. Note that it fetches an <em>object</em>, which need not be a module. Importing a module for the first time results in a module object being put in <cite>sys.modules</cite>, so usually when you import something you get a module back. This need not be the case however.</p> <p>This means you can use <a class="reference internal" href="unittest.mock.html#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> to <em>temporarily</em> put a mock in place in <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>. Any imports whilst this patch is active will fetch the mock. When the patch is complete (the decorated function exits, the with statement body is complete or <code class="docutils literal notranslate"><span class="pre">patcher.stop()</span></code> is called) then whatever was there previously will be restored safely.</p> <p>Here’s an example that mocks out the ‘fooble’ module.</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="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="p">{</span><span class="s1">'fooble'</span><span class="p">:</span> <span class="n">mock</span><span class="p">}):</span> <span class="gp">... </span> <span class="kn">import</span> <span class="nn">fooble</span> <span class="gp">... </span> <span class="n">fooble</span><span class="o">.</span><span class="n">blob</span><span class="p">()</span> <span class="gp">...</span> <span class="go"><Mock name='mock.blob()' id='...'></span> <span class="gp">>>> </span><span class="k">assert</span> <span class="s1">'fooble'</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">blob</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">()</span> </pre></div> </div> <p>As you can see the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">fooble</span></code> succeeds, but on exit there is no ‘fooble’ left in <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>.</p> <p>This also works for the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">name</span></code> form:</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="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="p">{</span><span class="s1">'fooble'</span><span class="p">:</span> <span class="n">mock</span><span class="p">}):</span> <span class="gp">... </span> <span class="kn">from</span> <span class="nn">fooble</span> <span class="k">import</span> <span class="n">blob</span> <span class="gp">... </span> <span class="n">blob</span><span class="o">.</span><span class="n">blip</span><span class="p">()</span> <span class="gp">...</span> <span class="go"><Mock name='mock.blob.blip()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">blob</span><span class="o">.</span><span class="n">blip</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">()</span> </pre></div> </div> <p>With slightly more work you can also mock package imports:</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">modules</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'package'</span><span class="p">:</span> <span class="n">mock</span><span class="p">,</span> <span class="s1">'package.module'</span><span class="p">:</span> <span class="n">mock</span><span class="o">.</span><span class="n">module</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="s1">'sys.modules'</span><span class="p">,</span> <span class="n">modules</span><span class="p">):</span> <span class="gp">... </span> <span class="kn">from</span> <span class="nn">package.module</span> <span class="k">import</span> <span class="n">fooble</span> <span class="gp">... </span> <span class="n">fooble</span><span class="p">()</span> <span class="gp">...</span> <span class="go"><Mock name='mock.module.fooble()' id='...'></span> <span class="gp">>>> </span><span class="n">mock</span><span class="o">.</span><span class="n">module</span><span class="o">.</span><span class="n">fooble</span><span class="o">.</span><span class="n">assert_called_once_with</span><span class="p">()</span> </pre></div> </div> </div> <div class="section" id="tracking-order-of-calls-and-less-verbose-call-assertions"> <h3>Tracking order of calls and less verbose call assertions<a class="headerlink" href="#tracking-order-of-calls-and-less-verbose-call-assertions" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="unittest.mock.html#unittest.mock.Mock" title="unittest.mock.Mock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mock</span></code></a> class allows you to track the <em>order</em> of method calls on your mock objects through the <a class="reference internal" href="unittest.mock.html#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> attribute. This doesn’t allow you to track the order of calls between separate mock objects, however we can use <a class="reference internal" href="unittest.mock.html#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> to achieve the same effect.</p> <p>Because mocks track calls to child mocks in <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code>, and accessing an arbitrary attribute of a mock creates a child mock, we can create our separate mocks from a parent one. Calls to those child mock will then all be recorded, in order, in the <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code> of the parent:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">manager</span> <span class="o">=</span> <span class="n">Mock</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">mock_foo</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">foo</span> <span class="gp">>>> </span><span class="n">mock_bar</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">bar</span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">mock_foo</span><span class="o">.</span><span class="n">something</span><span class="p">()</span> <span class="go"><Mock name='mock.foo.something()' id='...'></span> <span class="gp">>>> </span><span class="n">mock_bar</span><span class="o">.</span><span class="n">other</span><span class="o">.</span><span class="n">thing</span><span class="p">()</span> <span class="go"><Mock name='mock.bar.other.thing()' id='...'></span> </pre></div> </div> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">manager</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call.foo.something(), call.bar.other.thing()]</span> </pre></div> </div> <p>We can then assert about the calls, including the order, by comparing with the <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code> attribute on the manager mock:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">expected_calls</span> <span class="o">=</span> <span class="p">[</span><span class="n">call</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">something</span><span class="p">(),</span> <span class="n">call</span><span class="o">.</span><span class="n">bar</span><span class="o">.</span><span class="n">other</span><span class="o">.</span><span class="n">thing</span><span class="p">()]</span> <span class="gp">>>> </span><span class="n">manager</span><span class="o">.</span><span class="n">mock_calls</span> <span class="o">==</span> <span class="n">expected_calls</span> <span class="go">True</span> </pre></div> </div> <p>If <code class="docutils literal notranslate"><span class="pre">patch</span></code> is creating, and putting in place, your mocks then you can attach them to a manager mock using the <a class="reference internal" href="unittest.mock.html#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. After attaching calls will be recorded in <code class="docutils literal notranslate"><span class="pre">mock_calls</span></code> of the manager.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">manager</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">'mymodule.Class1'</span><span class="p">)</span> <span class="k">as</span> <span class="n">MockClass1</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">'mymodule.Class2'</span><span class="p">)</span> <span class="k">as</span> <span class="n">MockClass2</span><span class="p">:</span> <span class="gp">... </span> <span class="n">manager</span><span class="o">.</span><span class="n">attach_mock</span><span class="p">(</span><span class="n">MockClass1</span><span class="p">,</span> <span class="s1">'MockClass1'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">manager</span><span class="o">.</span><span class="n">attach_mock</span><span class="p">(</span><span class="n">MockClass2</span><span class="p">,</span> <span class="s1">'MockClass2'</span><span class="p">)</span> <span class="gp">... </span> <span class="n">MockClass1</span><span class="p">()</span><span class="o">.</span><span class="n">foo</span><span class="p">()</span> <span class="gp">... </span> <span class="n">MockClass2</span><span class="p">()</span><span class="o">.</span><span class="n">bar</span><span class="p">()</span> <span class="gp">...</span> <span class="go"><MagicMock name='mock.MockClass1().foo()' id='...'></span> <span class="go"><MagicMock name='mock.MockClass2().bar()' id='...'></span> <span class="gp">>>> </span><span class="n">manager</span><span class="o">.</span><span class="n">mock_calls</span> <span class="go">[call.MockClass1(),</span> <span class="go"> call.MockClass1().foo(),</span> <span class="go"> call.MockClass2(),</span> <span class="go"> call.MockClass2().bar()]</span> </pre></div> </div> <p>If many calls have been made, but you’re only interested in a particular sequence of them then an alternative is to use the <a class="reference internal" href="unittest.mock.html#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> method. This takes a list of calls (constructed with the <a class="reference internal" href="unittest.mock.html#unittest.mock.call" title="unittest.mock.call"><code class="xref py py-data docutils literal notranslate"><span class="pre">call</span></code></a> object). If that sequence of calls are in <a class="reference internal" href="unittest.mock.html#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> then the assert succeeds.</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="o">.</span><span class="n">foo</span><span class="p">()</span><span class="o">.</span><span class="n">bar</span><span class="p">()</span><span class="o">.</span><span class="n">baz</span><span class="p">()</span> <span class="go"><MagicMock name='mock().foo().bar().baz()' id='...'></span> <span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">one</span><span class="p">()</span><span class="o">.</span><span class="n">two</span><span class="p">()</span><span class="o">.</span><span class="n">three</span><span class="p">()</span> <span class="go"><MagicMock name='mock.one().two().three()' id='...'></span> <span class="gp">>>> </span><span class="n">calls</span> <span class="o">=</span> <span class="n">call</span><span class="o">.</span><span class="n">one</span><span class="p">()</span><span class="o">.</span><span class="n">two</span><span class="p">()</span><span class="o">.</span><span class="n">three</span><span class="p">()</span><span class="o">.</span><span class="n">call_list</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">m</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> </pre></div> </div> <p>Even though the chained call <code class="docutils literal notranslate"><span class="pre">m.one().two().three()</span></code> aren’t the only calls that have been made to the mock, the assert still succeeds.</p> <p>Sometimes a mock may have several calls made to it, and you are only interested in asserting about <em>some</em> of those calls. You may not even care about the order. In this case you can pass <code class="docutils literal notranslate"><span class="pre">any_order=True</span></code> to <code class="docutils literal notranslate"><span class="pre">assert_has_calls</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="gp">>>> </span><span class="n">m</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">m</span><span class="o">.</span><span class="n">two</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">m</span><span class="o">.</span><span class="n">seven</span><span class="p">(</span><span class="mi">7</span><span class="p">),</span> <span class="n">m</span><span class="o">.</span><span class="n">fifty</span><span class="p">(</span><span class="s1">'50'</span><span class="p">)</span> <span class="go">(...)</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="o">.</span><span class="n">fifty</span><span class="p">(</span><span class="s1">'50'</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="o">.</span><span class="n">seven</span><span class="p">(</span><span class="mi">7</span><span class="p">)]</span> <span class="gp">>>> </span><span class="n">m</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> </div> <div class="section" id="more-complex-argument-matching"> <h3>More complex argument matching<a class="headerlink" href="#more-complex-argument-matching" title="Permalink to this headline">¶</a></h3> <p>Using the same basic concept as <a class="reference internal" href="unittest.mock.html#unittest.mock.ANY" title="unittest.mock.ANY"><code class="xref py py-data docutils literal notranslate"><span class="pre">ANY</span></code></a> we can implement matchers to do more complex assertions on objects used as arguments to mocks.</p> <p>Suppose we expect some object to be passed to a mock that by default compares equal based on object identity (which is the Python default for user defined classes). To use <a class="reference internal" href="unittest.mock.html#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> we would need to pass in the exact same object. If we are only interested in some of the attributes of this object then we can create a matcher that will check these attributes for us.</p> <p>You can see in this example how a ‘standard’ call to <code class="docutils literal notranslate"><span class="pre">assert_called_with</span></code> isn’t sufficient:</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="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</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="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</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">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="n">Foo</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">mock</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="n">Foo</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="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected: call(<__main__.Foo object at 0x...>)</span> <span class="go">Actual call: call(<__main__.Foo object at 0x...>)</span> </pre></div> </div> <p>A comparison function for our <code class="docutils literal notranslate"><span class="pre">Foo</span></code> class might look something like this:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">compare</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span> <span class="gp">... </span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">==</span> <span class="nb">type</span><span class="p">(</span><span class="n">other</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="kc">False</span> <span class="gp">... </span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">!=</span> <span class="n">other</span><span class="o">.</span><span class="n">a</span><span class="p">:</span> <span class="gp">... </span> <span class="k">return</span> <span class="kc">False</span> <span class="gp">... </span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span> <span class="o">!=</span> <span class="n">other</span><span class="o">.</span><span class="n">b</span><span class="p">:</span> <span class="gp">... </span> <span class="k">return</span> <span class="kc">False</span> <span class="gp">... </span> <span class="k">return</span> <span class="kc">True</span> <span class="gp">...</span> </pre></div> </div> <p>And a matcher object that can use comparison functions like this for its equality operation would look something like this:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">Matcher</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="n">compare</span><span class="p">,</span> <span class="n">some_obj</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">compare</span> <span class="o">=</span> <span class="n">compare</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">some_obj</span> <span class="o">=</span> <span class="n">some_obj</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</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">compare</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">some_obj</span><span class="p">,</span> <span class="n">other</span><span class="p">)</span> <span class="gp">...</span> </pre></div> </div> <p>Putting all this together:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">match_foo</span> <span class="o">=</span> <span class="n">Matcher</span><span class="p">(</span><span class="n">compare</span><span class="p">,</span> <span class="n">Foo</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">mock</span><span class="o">.</span><span class="n">assert_called_with</span><span class="p">(</span><span class="n">match_foo</span><span class="p">)</span> </pre></div> </div> <p>The <code class="docutils literal notranslate"><span class="pre">Matcher</span></code> is instantiated with our compare function and the <code class="docutils literal notranslate"><span class="pre">Foo</span></code> object we want to compare against. In <code class="docutils literal notranslate"><span class="pre">assert_called_with</span></code> the <code class="docutils literal notranslate"><span class="pre">Matcher</span></code> equality method will be called, which compares the object the mock was called with against the one we created our matcher with. If they match then <code class="docutils literal notranslate"><span class="pre">assert_called_with</span></code> passes, and if they don’t an <a class="reference internal" href="exceptions.html#AssertionError" title="AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> is raised:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">match_wrong</span> <span class="o">=</span> <span class="n">Matcher</span><span class="p">(</span><span class="n">compare</span><span class="p">,</span> <span class="n">Foo</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">assert_called_with</span><span class="p">(</span><span class="n">match_wrong</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="o">...</span> <span class="gr">AssertionError</span>: <span class="n">Expected: ((<Matcher object at 0x...>,), {})</span> <span class="go">Called with: ((<Foo object at 0x...>,), {})</span> </pre></div> </div> <p>With a bit of tweaking you could have the comparison function raise the <a class="reference internal" href="exceptions.html#AssertionError" title="AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> directly and provide a more useful failure message.</p> <p>As of version 1.5, the Python testing library <a class="reference external" href="https://pyhamcrest.readthedocs.io/">PyHamcrest</a> provides similar functionality, that may be useful here, in the form of its equality matcher (<a class="reference external" href="https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality">hamcrest.library.integration.match_equality</a>).</p> </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> — getting started</a><ul> <li><a class="reference internal" href="#using-mock">Using Mock</a><ul> <li><a class="reference internal" href="#mock-patching-methods">Mock Patching Methods</a></li> <li><a class="reference internal" href="#mock-for-method-calls-on-an-object">Mock for Method Calls on an Object</a></li> <li><a class="reference internal" href="#mocking-classes">Mocking Classes</a></li> <li><a class="reference internal" href="#naming-your-mocks">Naming your mocks</a></li> <li><a class="reference internal" href="#tracking-all-calls">Tracking all Calls</a></li> <li><a class="reference internal" href="#setting-return-values-and-attributes">Setting Return Values and Attributes</a></li> <li><a class="reference internal" href="#raising-exceptions-with-mocks">Raising exceptions with mocks</a></li> <li><a class="reference internal" href="#side-effect-functions-and-iterables">Side effect functions and iterables</a></li> <li><a class="reference internal" href="#creating-a-mock-from-an-existing-object">Creating a Mock from an Existing Object</a></li> </ul> </li> <li><a class="reference internal" href="#patch-decorators">Patch Decorators</a></li> <li><a class="reference internal" href="#further-examples">Further Examples</a><ul> <li><a class="reference internal" href="#mocking-chained-calls">Mocking chained calls</a></li> <li><a class="reference internal" href="#partial-mocking">Partial mocking</a></li> <li><a class="reference internal" href="#mocking-a-generator-method">Mocking a Generator Method</a></li> <li><a class="reference internal" href="#applying-the-same-patch-to-every-test-method">Applying the same patch to every test method</a></li> <li><a class="reference internal" href="#mocking-unbound-methods">Mocking Unbound Methods</a></li> <li><a class="reference internal" href="#checking-multiple-calls-with-mock">Checking multiple calls with mock</a></li> <li><a class="reference internal" href="#coping-with-mutable-arguments">Coping with mutable arguments</a></li> <li><a class="reference internal" href="#nesting-patches">Nesting Patches</a></li> <li><a class="reference internal" href="#mocking-a-dictionary-with-magicmock">Mocking a dictionary with MagicMock</a></li> <li><a class="reference internal" href="#mock-subclasses-and-their-attributes">Mock subclasses and their attributes</a></li> <li><a class="reference internal" href="#mocking-imports-with-patch-dict">Mocking imports with patch.dict</a></li> <li><a class="reference internal" href="#tracking-order-of-calls-and-less-verbose-call-assertions">Tracking order of calls and less verbose call assertions</a></li> <li><a class="reference internal" href="#more-complex-argument-matching">More complex argument matching</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="unittest.mock.html" title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest.mock</span></code> — mock object library</a></p> <h4>Next topic</h4> <p class="topless"><a href="2to3.html" title="next chapter">2to3 - Automated Python 2 to 3 code translation</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-examples.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="2to3.html" title="2to3 - Automated Python 2 to 3 code translation" >next</a> |</li> <li class="right" > <a href="unittest.mock.html" title="unittest.mock — mock object library" >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>