Using pytest
Prepare an example
Create a new file named car.py and add the following code. It defines a Car
class with two methods: accelerate
and brake
:
Now create a test file named test_car.py with the following code:
In both examples, we import the Car
class from car.py and create an instance of Car
with an initial speed of 30.
The test_accelerate
and test_brake
functions or methods check that the corresponding Car
methods behave as expected.
Note that pytest only runs functions whose names start with test
.
Run tests
If JetBrains Fleet is in Smart Mode, and a Python interpreter has been configured for the project workspace, you will see run icons in the gutter next to test method definitions. You can use these icons to run each test individually:

To run all tests at once, you can create a run configuration. Click the Run icon (⌘ R) and select Create Run Configurations in run.json.
A run configuration for pytest must include "type": "python-tests"
and "testFramework": "pytest"
. You also need to specify the test file name in the targets
field:
To run the configuration, press ⌘ R. The terminal will display the test results:

Fix failing tests
The test_brake
method has failed. Click it in the left pane to see the reason:

We expected the car's speed to be 25 after braking, but it was actually 30. Why did this happen? The tests ran sequentially, and test_accelerate
changed the initial speed of the car. To prevent this, we need to reinitializes the car inside each test:
Now rerun the test_my_car configuration and verify that all tests pass:

Use tests to locate issues
Tests are designed to reveal problems in code. When you press the brake pedal in a real car, it should either slow down or stop completely, depending on the current speed. Let's check if the same is true for our Car
class.
The following test uses parametrization. Add it to test_car.py:
Also, add the following import
statement to the beginning of the test_car.py file: import pytest
.
After running the test, you will see that it executes 100 times, using speeds in the range from 0 to 100. At each speed, the car is braked, and then we calculate how far it would travel in one hour with the new speed. That distance must be equal to or greater than zero.
Run the tests:

If you click one of the failed test_move
cases, you will see that it failed because the distance was negative.
Modify the brake
method of the Car
class to stop the car completely when its speed is 5 or less:
Now all tests pass:
