Unit Testing
Last updated
Last updated
Unit testing Cement apps is as straight forward as any other Python library. Cement uses, and recommends the following utilities, but there are no limitations to what tools you choose to use:
: Unit testing.
: Monitors code while unit tests run to ensure all code is tested.
: Style-guide enforcement
Cement has a strict policy that all framework code has 100% test coverage, and 100% style-guide clearance before any releases are published. This is not required for applications built on Cement, but it is highly recommended for quality.
For examples, feel free to browse the on Github.
Cement apps sub-class from , however for testing there are some things we want to override to make things more portable/reliable. For example, in testing we do not want to parse ~/.myapp.yml
(example local user configuration file), as this may skew tests from one developer machine to the next.
Cement includes an additional that can also be sub-classed to easily override App.Meta for testing.
This looks something like:
To use this class, it is best to create a separate MyAppTest
class that sub-classes both from TestApp
and your MyApp
:
The above is equivalent to running the following at the command line:
myapp/tests/conftest.py:
This creates a tmp
fixture that we can use anywhere in our tests, and most importantly when the test is complete the temp object (file and directory) are automatically removed.
myapp/tests/test_myapp.py:
In Pytest, tests are loaded from files matching test_
, and functions matching test_
. Some developers prefer to keep tests alongside the file it is testing (for example: main.py
and test_main.py
). Cement developers prefer putting all tests in a separate tests/
directory:
A typical test is just a simple function that executes some logic, and asserts some conditions:
In the above example, we tested two conditions (whether --debug
was passed or not), and asserted those conditions. If either assertion failed, the test would fail.
Running tests with Pytest can be done by running pytest
in the root of your project directory. That said, to add support for coverage.py you likely want to create a helper script (Makefile, Fabric, etc) to execute all the things at once.
Cement generate project
includes support for coverage.py
out of the box, and also includes a Makefile
with helpers:
myapp/Makefile:
And this is run by:
As most apps built on Cement are command-line based, passing arguments and options to MyApp
is important. This is easily handled by passing the list:
Working with files and directories is common for apps built on Cement, which can be easily done using the utility in combination with . These fixtures can be automatically loaded from tests/conftest.py
: