How to improve pytest performance by clearing pytest cache and results in VSCode
The aim of this page📝 is to explain how to clear pytest results and cache in Visual Studio Code based on the particular example of improving pytest performance. I was motivated to look into this because tests on a single module (say 20 tests) ran 10 seconds. Then I saw Dynamic run result in test explorer for pytest · Issue #21148 · microsoft/vscode-python. The best improvement came from simply running Clear all results, but try clearing cache, too.
2 min readAug 14, 2023
- The pytest cache is used to store data between test runs, such as the results of expensive computations or the state of external resources.
- Clearing the cache can improve performance by ensuring that tests are run with a clean slate.
- The
--cache-clear
flag can be used when running pytest to clear the cache at the start of the test run. - In Visual Studio Code, you can add the
--cache-clear
flag to your pytest configuration by opening the Command Palette and selectingPython: Configure Tests
. - Then, select the pytest test framework and the root directory containing your tests.
- In the
settings.json
file, find the"python.testing.pytestArgs"
setting and add"--cache-clear"
to the list of arguments.
{
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
"--cache-clear"
]
}
- The Test Explorer in Visual Studio Code provides an interface for running and debugging tests and analyzing test results.
- Clearing test results in the Test Explorer does not clear the pytest cache
- It also should not affect test performance — but in my case it did as I have not done that in months
- Test results can be cleared manually by clicking on the “Clear all results” button in the Test Explorer or by running the “Clear all results” command from the Command Palette.
- Currently (unfortuntelly in my case), there is no built-in way to automatically clear test results in the Visual Studio Code Test Explorer.