One of key features of PyTest is the ability to create parametrized tests, meaning running test cases with various input values without having to write separate test cases.
Main goal of my most recent Django project is to develop better understanding of testing principles and tools. I have already built few Django applications, however never really focused on testing my own code - I was just happy the app “worked”.
Knowing what and how to test is a skill in itself. It is quite a challenge. One can write hundreds of test cases which are not really covering the essential functionalities, or they repeat. Just as most of the things, it comes with a practice. However, I understand the long-term value of writing and having effective tests.
Test Driven Development is a popular development approach when it comes to having the code effectively covered with tests.
One of the challenges in testing and in development in general is “staying DRY” - not repeating yourself. A lot of the times we need to test a functionality (for example forms) that require not only a lot of input values, but also several different combinations of these values. This can quickly lead to repeating yourself and having too many test cases.
Luckily, PyTest comes with @pytest.mark.parametrize
decorator which allows running single test case with multiple inputs.
Example
Typically, the @parametrize
decorator requires the following arguments and parameters:
- Test Parameters: These are the parameters you want to test your function with. They can be provided as a list of tuples or a list of dictionaries, where each tuple or dictionary represents a set of input parameters for your test function.
- Test Function: The test function that you want to parametrize. This function should accept arguments that match the parameters you specify in your test parameters.
Here’s a simple example of how I have covered user registration with parametrize:
|
|