Sophie

Sophie

distrib > Fedora > 18 > i386 > by-pkgid > 7f671eb35339cf812de52087b0d93519 > files > 271

python3-pytest-2.3.5-3.fc18.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Support for unittest.TestCase / Integration of fixtures</title>
    
    <link rel="stylesheet" href="_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '2.3.4.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </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>
    <link rel="top" title="None" href="index.html" />
    <link rel="up" title="py.test reference documentation" href="apiref.html" />
    <link rel="next" title="Running tests written for nose" href="nose.html" />
    <link rel="prev" title="Asserting deprecation and other warnings" href="recwarn.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="nose.html" title="Running tests written for nose"
             accesskey="N">next</a></li>
        <li class="right" >
          <a href="recwarn.html" title="Asserting deprecation and other warnings"
             accesskey="P">previous</a> |</li>
        <li><a href="contents.html">pytest-2.3.4.1</a> &raquo;</li>
          <li><a href="apiref.html" accesskey="U">py.test reference documentation</a> &raquo;</li>
 
<g:plusone></g:plusone>

      </ul>
    </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Search" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>

<h3>quicklinks</h3>
<div style="text-align: left; font-size: 100%; vertical-align: middle;">
<table>
<tr>
<td>
        <a href="index.html">home</a>
</td><td>
        <a href="contents.html">TOC/contents</a>
</td></tr><tr><td>
        <a href="getting-started.html">install</a>
</td><td>
        <a href="changelog.html">changelog</a>
</td></tr><tr><td>
        <a href="example/index.html">examples</a>
</td><td>
        <a href="customize.html">customize</a>
</td></tr><tr><td>
        <a href="https://bitbucket.org/hpk42/pytest/issues?status=new&status=open">issues[bb]</a>
</td><td>
        <a href="contact.html">contact</a>
</td></tr></table>
</div>

  <h3><a href="contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Support for unittest.TestCase / Integration of fixtures</a><ul>
<li><a class="reference internal" href="#usage">Usage</a></li>
<li><a class="reference internal" href="#mixing-pytest-fixtures-into-unittest-testcase-style-tests">Mixing pytest fixtures into unittest.TestCase style tests</a></li>
<li><a class="reference internal" href="#autouse-fixtures-and-accessing-other-fixtures">autouse fixtures and accessing other fixtures</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="recwarn.html"
                        title="previous chapter">Asserting deprecation and other warnings</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="nose.html"
                        title="next chapter">Running tests written for nose</a></p>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="support-for-unittest-testcase-integration-of-fixtures">
<span id="unittest-testcase"></span><h1>Support for unittest.TestCase / Integration of fixtures<a class="headerlink" href="#support-for-unittest-testcase-integration-of-fixtures" title="Permalink to this headline">¶</a></h1>
<p>py.test has support for running Python <a class="reference external" href="http://docs.python.org/library/unittest.html">unittest.py style</a> tests.
It&#8217;s meant for leveraging existing unittest-style projects
to use pytest features.  Concretely, pytest will automatically
collect <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> subclasses and their <tt class="docutils literal"><span class="pre">test</span></tt> methods in
test files.  It will invoke typical setup/teardown methods and
generally try to make test suites written to run on unittest, to also
run using <tt class="docutils literal"><span class="pre">py.test</span></tt>.  We assume here that you are familiar with writing
<tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> style tests and rather focus on
integration aspects.</p>
<div class="section" id="usage">
<h2>Usage<a class="headerlink" href="#usage" title="Permalink to this headline">¶</a></h2>
<p>After <a class="reference internal" href="getting-started.html#installation"><em>Installation</em></a> type:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">py</span><span class="o">.</span><span class="n">test</span>
</pre></div>
</div>
<p>and you should be able to run your unittest-style tests if they
are contained in <tt class="docutils literal"><span class="pre">test_*</span></tt> modules.  If that works for you then
you can make use of most <a class="reference internal" href="index.html#features"><em>pytest features</em></a>, for example
<tt class="docutils literal"><span class="pre">--pdb</span></tt> debugging in failures, using <a class="reference internal" href="assert.html#assert"><em>plain assert-statements</em></a>,
<a class="reference internal" href="example/reportingdemo.html#tbreportdemo"><em>more informative tracebacks</em></a>, stdout-capturing or
distributing tests to multiple CPUs via the <tt class="docutils literal"><span class="pre">-nNUM</span></tt> option if you
installed the <tt class="docutils literal"><span class="pre">pytest-xdist</span></tt> plugin.  Please refer to
the general pytest documentation for many more examples.</p>
</div>
<div class="section" id="mixing-pytest-fixtures-into-unittest-testcase-style-tests">
<h2>Mixing pytest fixtures into unittest.TestCase style tests<a class="headerlink" href="#mixing-pytest-fixtures-into-unittest-testcase-style-tests" title="Permalink to this headline">¶</a></h2>
<p>Running your unittest with <tt class="docutils literal"><span class="pre">py.test</span></tt> allows you to use its
<a class="reference internal" href="fixture.html#fixture"><em>fixture mechanism</em></a> with <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> style
tests.  Assuming you have at least skimmed the pytest fixture features,
let&#8217;s jump-start into an example that integrates a pytest <tt class="docutils literal"><span class="pre">db_class</span></tt>
fixture, setting up a class-cached database object, and then reference
it from a unittest-style test:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># content of conftest.py</span>

<span class="c"># we define a fixture function below and it will be &quot;used&quot; by</span>
<span class="c"># referencing its name from tests</span>

<span class="kn">import</span> <span class="nn">pytest</span>

<span class="nd">@pytest.fixture</span><span class="p">(</span><span class="n">scope</span><span class="o">=</span><span class="s">&quot;class&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">db_class</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">DummyDB</span><span class="p">:</span>
        <span class="k">pass</span>
    <span class="c"># set a class attribute on the invoking test context</span>
    <span class="n">request</span><span class="o">.</span><span class="n">cls</span><span class="o">.</span><span class="n">db</span> <span class="o">=</span> <span class="n">DummyDB</span><span class="p">()</span>
</pre></div>
</div>
<p>This defines a fixture function <tt class="docutils literal"><span class="pre">db_class</span></tt> which - if used - is
called once for each test class and which sets the class-level
<tt class="docutils literal"><span class="pre">db</span></tt> attribute to a <tt class="docutils literal"><span class="pre">DummyDB</span></tt> instance.  The fixture function
achieves this by receiving a special <tt class="docutils literal"><span class="pre">request</span></tt> object which gives
access to <a class="reference internal" href="fixture.html#request-context"><em>the requesting test context</em></a> such
as the <tt class="docutils literal"><span class="pre">cls</span></tt> attribute, denoting the class from which the fixture
is used.  This architecture de-couples fixture writing from actual test
code and allows re-use of the fixture by a minimal reference, the fixture
name.  So let&#8217;s write an actual <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> class using our
fixture definition:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># content of test_unittest_db.py</span>

<span class="kn">import</span> <span class="nn">unittest</span>
<span class="kn">import</span> <span class="nn">pytest</span>

<span class="nd">@pytest.mark.usefixtures</span><span class="p">(</span><span class="s">&quot;db_class&quot;</span><span class="p">)</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="k">def</span> <span class="nf">test_method1</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">assert</span> <span class="nb">hasattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="s">&quot;db&quot;</span><span class="p">)</span>
        <span class="k">assert</span> <span class="mi">0</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">db</span>   <span class="c"># fail for demo purposes</span>

    <span class="k">def</span> <span class="nf">test_method2</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">assert</span> <span class="mi">0</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">db</span>   <span class="c"># fail for demo purposes</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">&#64;pytest.mark.usefixtures(&quot;db_class&quot;)</span></tt> class-decorator makes sure that
the pytest fixture function <tt class="docutils literal"><span class="pre">db_class</span></tt> is called once per class.
Due to the deliberately failing assert statements, we can take a look at
the <tt class="docutils literal"><span class="pre">self.db</span></tt> values in the traceback:</p>
<div class="highlight-python"><pre>$ py.test test_unittest_db.py
=========================== test session starts ============================
platform linux2 -- Python 2.7.3 -- pytest-2.3.5
collected 2 items

test_unittest_db.py FF

================================= FAILURES =================================
___________________________ MyTest.test_method1 ____________________________

self = &lt;test_unittest_db.MyTest testMethod=test_method1&gt;

    def test_method1(self):
        assert hasattr(self, "db")
&gt;       assert 0, self.db   # fail for demo purposes
E       AssertionError: &lt;conftest.DummyDB instance at 0x19fdf38&gt;

test_unittest_db.py:9: AssertionError
___________________________ MyTest.test_method2 ____________________________

self = &lt;test_unittest_db.MyTest testMethod=test_method2&gt;

    def test_method2(self):
&gt;       assert 0, self.db   # fail for demo purposes
E       AssertionError: &lt;conftest.DummyDB instance at 0x19fdf38&gt;

test_unittest_db.py:12: AssertionError
========================= 2 failed in 0.02 seconds =========================</pre>
</div>
<p>This default pytest traceback shows that the two test methods
share the same <tt class="docutils literal"><span class="pre">self.db</span></tt> instance which was our intention
when writing the class-scoped fixture function above.</p>
</div>
<div class="section" id="autouse-fixtures-and-accessing-other-fixtures">
<h2>autouse fixtures and accessing other fixtures<a class="headerlink" href="#autouse-fixtures-and-accessing-other-fixtures" title="Permalink to this headline">¶</a></h2>
<p>Although it&#8217;s usually better to explicitely declare use of fixtures you need
for a given test, you may sometimes want to have fixtures that are
automatically used in a given context.  After all, the traditional
style of unittest-setup mandates the use of this implicit fixture writing
and chances are, you are used to it or like it.</p>
<p>You can flag fixture functions with <tt class="docutils literal"><span class="pre">&#64;pytest.fixture(autouse=True)</span></tt>
and define the fixture function in the context where you want it used.
Let&#8217;s look at an <tt class="docutils literal"><span class="pre">initdir</span></tt> fixture which makes all test methods of a
<tt class="docutils literal"><span class="pre">TestCase</span></tt> class execute in a temporary directory with a
pre-initialized <tt class="docutils literal"><span class="pre">samplefile.ini</span></tt>.  Our <tt class="docutils literal"><span class="pre">initdir</span></tt> fixture itself uses
the pytest builtin <a class="reference internal" href="tmpdir.html#tmpdir"><em>tmpdir</em></a> fixture to delegate the
creation of a per-test temporary directory:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># content of test_unittest_cleandir.py</span>
<span class="kn">import</span> <span class="nn">pytest</span>
<span class="kn">import</span> <span class="nn">unittest</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="nd">@pytest.fixture</span><span class="p">(</span><span class="n">autouse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">initdir</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tmpdir</span><span class="p">):</span>
        <span class="n">tmpdir</span><span class="o">.</span><span class="n">chdir</span><span class="p">()</span> <span class="c"># change to pytest-provided temporary directory</span>
        <span class="n">tmpdir</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s">&quot;samplefile.ini&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&quot;# testdata&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&quot;samplefile.ini&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
        <span class="k">assert</span> <span class="s">&quot;testdata&quot;</span> <span class="ow">in</span> <span class="n">s</span>
</pre></div>
</div>
<p>Due to the <tt class="docutils literal"><span class="pre">autouse</span></tt> flag the <tt class="docutils literal"><span class="pre">initdir</span></tt> fixture function will be
used for all methods of the class where it is defined.  This is a
shortcut for using a <tt class="docutils literal"><span class="pre">&#64;pytest.mark.usefixtures(&quot;initdir&quot;)</span></tt> marker
on the class like in the previous example.</p>
<p>Running this test module ...:</p>
<div class="highlight-python"><pre>$ py.test -q test_unittest_cleandir.py
.</pre>
</div>
<p>... gives us one passed test because the <tt class="docutils literal"><span class="pre">initdir</span></tt> fixture function
was executed ahead of the <tt class="docutils literal"><span class="pre">test_method</span></tt>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">While pytest supports receiving fixtures via <a class="reference internal" href="fixture.html#funcargs"><em>test function arguments</em></a> for non-unittest test methods, <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> methods cannot directly receive fixture
function arguments as implementing that is likely to inflict
on the ability to run general unittest.TestCase test suites.
Maybe optional support would be possible, though.  If unittest finally
grows a plugin system that should help as well.  In the meanwhile, the
above <tt class="docutils literal"><span class="pre">usefixtures</span></tt> and <tt class="docutils literal"><span class="pre">autouse</span></tt> examples should help to mix in
pytest fixtures into unittest suites.  And of course you can also start
to selectively leave away the <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> subclassing, use
plain asserts and get the unlimited pytest feature set.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="nose.html" title="Running tests written for nose"
             >next</a></li>
        <li class="right" >
          <a href="recwarn.html" title="Asserting deprecation and other warnings"
             >previous</a> |</li>
        <li><a href="contents.html">pytest-2.3.4.1</a> &raquo;</li>
          <li><a href="apiref.html" >py.test reference documentation</a> &raquo;</li>
 
<g:plusone></g:plusone>

      </ul>
    </div>

    <div class="footer">
        &copy; Copyright 2012, holger krekel.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
    </div>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-7597274-13']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

  </body>
</html>