Search code examples
pythonvisual-studio-codedebuggingpython-unittest

Debugging Python unittest in vscode behaves differently than normal test execution


OS is Windows 10 Python: 3.10 (same behavior in 3.11 and 3.9) This was previously working fine 10 days ago so I suspect a software update is to blame.

I'm trying to debug a simple python unittest in vscode using the test runner. It fails with a ModuleNotFound error but only when running the test in debug mode. When printing the sys.path, the root workspace directory is missing when running it via the debug option.

One other oddity is that when running a single unittest, I find the debugger is going into other test files and failing in those. I have to move them out of my testing directory.

Smallest File Tree

proj.
├───lib
│       main.py
│
└───test
        test_main.py

test_main contains:

from lib.main import m

Things I've Tried:

  • Cloned my entire vscode config over to MacOS and it works as expected. When checking the sys.path, the root directory is part of the debugger
  • Rolled VSCode back a few months of versions.
  • Rolled Pylance and Python extensions back a few months of versions as well.
  • Added the workspace path to the sys.path list but that causes errors further down the line with my azure cli that don't happen when running in regular execution.
  • settings.json python.testing.cwd does not contrinute to sys.path nor any other helpful configuration (also ruled out on macos operation by moving over all config files)
  • Disabled all VSCode extensions except for Python & Pylance

Any help here would be greatly appreciated! This ran fine one week ago!


Solution

  • You can open the Command Palette with Ctrl+Shift+P, type "Python: Configure Tests", and select the option that appears.

    enter image description here

    enter image description here

    Make sure that the root directory of your project is included in the test discovery path.

    If it still not work, you could add the root directory of your project to the PYTHONPATH environment variable. This can be done in the .env file in your workspace directory.

    One other oddity is that when running a single unittest, I find the debugger is going into other test files and failing in those. I have to move them out of my testing directory.

    By default, VS Code's Python extension will discover all test files in your workspace. You can do this by setting the name of the test file you want and setting it accordingly after the settings mentioned above. For example, you can just set the file to end with test and select *test.py in the settings.

    enter image description here