Setup Vscode With Python Unittest Python VSCode

Apr 23rd, 2021 - written by Kimserey with .

Few months ago we talked about Python Unittest. We looked at it from the perspective of running from terminal which is a great way to quickly verify that our application is healthy. When it comes to debugging specific issue, running from terminal can be more tricky. In this post, we will look at how we can enable Unittest test discovery from Visual Studio Code with the Python extension in order to provider a quick and easy way to debug source code and allowing us to breakpoint in unit tests.

Enable Unittest on VScode

To enable Unittest on VSCode, we run the commnad Discover test:

discover test

This will test prompt us to setup the testing framework used, pytest, nosetests or unittest, in this example I am using unittest.

Once configured, the settings file in .vscode/settings.json will be updated with the following:

1
2
3
4
5
6
{
  "python.testing.unittestArgs": ["-v", "-s", "./tests", "-p", "test_*.py"],
  "python.testing.pytestEnabled": false,
  "python.testing.nosetestsEnabled": false,
  "python.testing.unittestEnabled": true
}

This settings set the arguments used for Unittest and set Unittest as the Pyhthon testing framework used. The tests are under ./tests folder and the pattern used for the test files is test_*.

Run and Debug tests

Once we have Unittest setup with VSCode, we can then run the test from the Test tab.

test_result

Or we can click on top of each individual test or on top of the testcase class where we should now have the Run Test | Debug Test option.

run_test

Using Debug Test we can now easily breakpoint in our test, and in our own tested code.

debug

And that’s conclude today’s post!

Conclusion

In today’s post we saw how we could enable Unittest support in VSCode and enhance our development experience by being allow to quickly run and debug tests. Hope you liked this post and I see you on the next one!

External Sources

Designed, built and maintained by Kimserey Lam.