Here’s a neat way to embed tests in a module’s file, so that when the file is run standalone, the tests are called and run by default.

The trick is the standard if __name__ == "__main__": section that’s at the end of your Python file.  If you include your test classes in your module’s file, and you’re using Pytest, then the following at the end of your file will run the tests by default:

if __name__ == "__main__":
  import pytest
  pytest.main([__file__])

What’s going on here?

Well, if __name__ == "__main__": is usually included at the end of Python modules to specify what to run by default when the file is run from the command line.

And pytest.main() calls Pytest. It takes a list of parameters, so we pass it the name of the file itself, which is in the python variable __file__.

That doesn’t mean that the tests are run when the code is called as a module. As a module, the file still works the same way as if no tests were there.

So here’s an example of a “Hello, World!” file with a simple test, ready to be run by default:

example.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#! ./venv/bin/python3

class ExampleClass(object):
  @classmethod
  def example_method(self):
    return 'Hello, World!'

class TestExampleClass(object):
  def test_hello_world(self):
    assert(ExampleClass.example_method() == 'Hello, World!')

if __name__ == "__main__":
  import pytest
  pytest.main([__file__])

 

The she-bang (#!) on line 1 just points to the Python in my virtualenv. Set the she-bang line to point to whatever version of Python works for you.

To run this, don’t forget to make the file executable from the command-line:
> chmod +x example.py

…and also make sure that pytest is installed:
> pip install pytest

So now you can run the tests just by calling the file:
> ./example.py

Note that for large projects, you probably want your tests in separate files, and in a separate /test folder. But this is convenient for small modules.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Set your Twitter account name in your settings to use the TwitterBar Section.