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:
What’s going on here?
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.
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
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:
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:
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.