Python: how to create a positive test for procedures?
<p>I have a class with some <code>@staticmethod</code>'s that are procedures, thus they do not return anything / their return type is <code>None</code>.</p>

<p>If they fail during their execution, they throw an <code>Exception</code>.</p>

<p>I want to <code>unittest</code> this class, but I am struggling with designing positive tests.</p>

<p>For negative tests this task is easy:</p>

<pre><code>assertRaises(ValueError, my_static_method(*args))
assertRaises(MyCustomException, my_static_method(*args))
</code></pre>

<p>...but how do I create positive tests? Should I redesign my procedures to always return <code>True</code> after execution, so that I can use <code>assertTrue</code> on them?</p>

<p>Without seeing the actual code it is hard to guess, however I will make some assumptions:</p>

<ol>
<li>The logic in the static methods is deterministic. </li>
<li>After doing some calculation on the input value there is a result
and some operation is done with this result. </li>
<li>python3.4 (mock has evolved and moved over the last few versions)</li>
</ol>

<p>In order to test code one has to check that at least in the end it produces the expected results. If there is no return value then the result is usually stored or send somewhere. In this case we can check that the method that stores or sends the result is called with the expected arguments.</p>

<p>This can be done with the tools available in the <code>mock</code> package that has become part of the <code>unittest</code> package.</p>

<p>e.g. the following static method in <code>my_package/my_module.py</code>:</p>

<pre><code>import uuid

class MyClass:

    @staticmethod
    def my_procedure(value):
        if isinstance(value, str):
            prefix = 'string'
        else:
            prefix = 'other'

        with open('/tmp/%s_%s' % (prefix, uuid.uuid4()), 'w') as f:
            f.write(value)
</code></pre>

<p>In the unit test I will check the following:</p>

<ol>
<li><code>open</code> has been called.</li>
<li>The expected file name has been calculated.</li>
<li><code>open</code>has been called in <code>write</code> mode.</li>
<li>The <code>write()</code> method of the file handle has been called with the expected argument.</li>
</ol>

<p>Unittest:</p>

<pre><code>import unittest
from unittest.mock import patch

from my_package.my_module import MyClass


class MyClassTest(unittest.TestCase):
    @patch('my_package.my_module.open', create=True)
    def test_my_procedure(self, open_mock):
        write_mock = open_mock.return_value.write
        MyClass.my_procedure('test')
        self.assertTrue(open_mock.call_count, 1)
        file_name, mode = open_mock.call_args[0]
        self.assertTrue(file_name.startswith('/tmp/string_'))
        self.assertEqual(mode, 'w')
        self.assertTrue(write_mock.called_once_with('test'))
</code></pre>

python unit-testing static-methods assert procedure