Step 3. Test your first Python application
Remember, in the first tutorial you’ve created your first Python application, and in the second tutorial you’ve debugged it. Now it’s time to do some testing. Let's modify the
brake method of the code sample:
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 run the test by clicking the Run icon in the gutter near the class definition. A Run/Debug configuration will be created automatically: 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:
Now let's run the tests. Right-click the test_Car.py editor tab and choose Run 'Unittests in test_Car.py':
This time some tests pass successfully:
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, click in the Navigation bar, or right-click the editor background at the method
test_should_not_allow_negative_speed and choose Debug from the context menu:
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 button again, and see the test debug output:
It shows that speed can become negative, which is impossible. It seems that some additional code is required in the class
Change the method
brake as follows:
Now let's run the tests again. Switch to test_car.py and click in the Navigation bar:
All tests have passed.
Running tests automatically
In the last paragraph, after fixing our code, we reran our tests by using the button. 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.