Testing class methods with pytest
<p>In the documentation of pytest various examples for test cases are listed. Most of them show the test of functions. But Iâm missing an example of how to test classes and class methods. Letâs say we have the following class in the module <code>cool.py</code> we like to test:</p>

<pre><code>class SuperCool(object):

    def action(self, x):
        return x * x
</code></pre>

<p>How does the according test class in <code>tests/test_cool.py</code> have to look?</p>

<pre><code>class TestSuperCool():

    def test_action(self, x):
        pass
</code></pre>

<p>How can <code>test_action()</code> be used to test <code>action()</code>?</p>

<p>Well, one way is to just create your object within the test method and interact with it from there: </p>

<pre><code>def test_action(self, x):
    o = SuperCool()
    assert o.action(2) == 4
</code></pre>

<p>You can apparently use something like the classic <code>setup</code> and <code>teardown</code> style unittest using the methods here: <a href="http://doc.pytest.org/en/latest/xunit_setup.html" rel="nofollow">http://doc.pytest.org/en/latest/xunit_setup.html</a></p>

<p>I'm not 100% how they are used because the documentation for pytest is <em>terrible</em>. </p>

<p>edit: yeah so apparently if you do something like </p>

<pre><code>class TestSuperCool():
    def setup(self):
        self.sc = SuperCool()

    ... 

    # test using self.sc down here
</code></pre>

python py.test