JetBrains Fleet 1.48 Help

Using unittest

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:

class Car: def __init__(self, speed=0): self.speed = speed def accelerate(self): self.speed += 5 def brake(self): self.speed -= 5

Now create a test file named test_car.py with the following code:

from unittest import TestCase from car import Car class TestCar(TestCase): car = Car(30) def test_accelerate(self): self.car.accelerate() self.assertEqual(self.car.speed, 35) def test_brake(self): self.car.brake() self.assertEqual(self.car.speed, 25)

In both examples, we import the Car class from car.py, define TestCar as a subclass of unittest.TestCase, 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.

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:

Gutter icons for unittest tests

Alternatively, you can create a run configuration. Click the Run icon (⌘ R) and select Create Run Configurations in run.json.

A run configuration for unittest must include "type": "python-tests" and "testFramework": "unittest". You also need to specify the test file name in the targets field:

{ "type": "python-tests", "name": "test_my_car", "testFramework": "unittest", "targets": ["test_car"] }

To run the configuration, press ⌘ R. The terminal will display the test results:

Unittest results in terminal

Fix failing tests

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

Details of the failed test_brake method

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 implement a setUp() method that reinitializes the car before each test method is run:

from unittest import TestCase from car import Car class TestCar(TestCase): def setUp(self): self.car = Car(30) def test_accelerate(self): self.car.accelerate() self.assertEqual(self.car.speed, 35) def test_brake(self): self.car.brake() self.assertEqual(self.car.speed, 25)

Now rerun the test_my_car configuration and verify that all tests pass:

All unittest tests passed
19 May 2025