Step 3. Test your first Python application
Choosing the test runner
To explicitly set the required test runner in the project settings, press Ctrl+Alt+S to open the IDE settings and select Tools | Python Integrated Tools, and then select the target test runner from the Default test runner list.
For more details, see Testing frameworks.
A quick way to create tests is to have PyCharm stub them out from the class we’d like to test. To do this, we need to open Car.py, then right-click the name of the class, point to , and then choose (or just press Ctrl+Shift+T):
A popup appears that suggests to create a new test:
OK, let’s do it. We are going to test whether our car is able to accelerate and brake, so let's select those checkboxes:
A new Python test class is created:
You can create a Run/Debug configuration for the test and run it. However, we can see that the test fails by default:
Now we know that we can run tests, let’s start writing some actual test code.
How to write unit tests is out of scope for this article. If you’re interested in learning about using the `unittest` framework, you can check out their docs.
For our example let’s use these tests:
Running the test
Now run the test by right-clicking the editor background above the declaration of the class
test_car. This time some of the tests pass successfully:
Debugging the test
Next, let's look deeper into the test code and debug one of the tests that failed. For example, we'll put a breakpoint in the following place:
Next, launch a debugger session. To do that, right-click the editor background at the method
test_should_not_allow_negative_speed and choose Debug from the context menu, or click in the Navigation bar:
We've placed the breakpoint at the
self.car.brake() statement of the
test_should_not_allow_negative_speed method. Let's look at the debugger output:
Click the button to skip the library classes and go into the class
Next, click the same button again, and see the test debug output:
It shows that speed can become negative, which is impossible. It seems that some additional check is required in the code of the class
Change the method
brake as follows:
Now let's run the test again:
Running tests automatically
In the last paragraph, after fixing our code, we reran our tests by using the icon. If you'd like to focus on your code, and just see when you've resolved the issue, PyCharm can run the tests for you automatically.