pytest parametrize class method:
Pytest allows you to parametrize test functions using @pytest.mark.parametrize
decorator. This decorator can also be used to parametrize test methods in a class.
To parametrize a class method, you can define the decorator above the method declaration, providing the parameter values as arguments. The method will be executed for each set of parameter values.
Let’s consider an example to understand this:
import pytest class MathOperations: @pytest.mark.parametrize("a, b, expected", [ (2, 3, 5), (5, 7, 12), (-3, 2, -1), ]) def test_addition(self, a, b, expected): result = MathOperations.add(a, b) assert result == expected @staticmethod def add(a, b): return a + b
In the above example, we have a class MathOperations
with a method add
that performs addition. We want to test this method with different input values using the test_addition
test method.
The @pytest.mark.parametrize
decorator is used to parametrize the test_addition
method. The decorator is followed by parameter names (“a”, “b”, “expected”) and a list of tuples representing different sets of parameter values.
When the test is executed, the test_addition
method is executed for each set of parameter values. The values are then passed to the method as arguments and the test assertions are performed.
For example, in the first iteration, a = 2
, b = 3
, and expected = 5
. The add
method is called with these values, and the returned result is compared with the expected value (5
).
If all assertions pass for each set of parameters, the test case is considered passed. Otherwise, if one or more assertions fail, the test case is considered failed.
- Powershell send email without credentials
- Psql: error: connection to server on socket “/tmp/.s.pgsql.5432” failed: connection refused is the server running locally and accepting connections on that socket?
- Provider id must be specified for client registration ‘azure’
- Psycopg2 ld: library not found for -lssl
- Pytest no module named src