Python Unittest: No tests discovered in Visual Studio Code

There are 2 reasons that this might not work:

There is an error in the tests

The python Testing plugin won't find your tests if there is an error in the test script.

To check for a potential error, click the Show Test Output, then run the tests using Run All Tests (both buttons are located in the top left, just above where the tests should appear).

If there is an error, it will appear in the OUTPUT tab.

The tests aren't properly configured

Check your .vscode/settings.json, and take the python.testing.unittestArgs list.

You can debug the discovery of tests in the command line by adding args to the python3 -m unittest discover command in the command line.

So with this config:

{
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        ".",
        "-p",
        "*test*.py"
    ]
}

You would launch the command:

python3 -m unittest discover -v -s . -p "*test*.py"

You can play with the args unitl you discover your tests, and modify the args in .vscode/settings.json accordingly .

Here are the docs for unittest

Note

A common reason for this is that you're trying to run tests with dependencies. If this is the case, you can select your interpreter by running ctrl + shift + p and searching Python: Select Interpreter, then selecting the correct interpreter.


The problem was that I was using relative imports in the test module (from ..utils import guards). I just changed it to absolute import (from app.utils import guards) and it all worked again.


It is because some of the imports in the test is not discoverable. when running python -m unittest -h, the last line of the output is

For test discovery all test modules must be importable from the top level directory of the project.

it is likely that VSCode is running the command without the right PYTHONPATH and other environment variables.

I created __init__.py and put the following code into it.

import sys
import os
import unittest

# set module path for testing
sys.path.insert(0, "path_in_PYTHONPATH")
# repead to include all paths

class TestBase(unittest.TestCase):
    def __init__(self, methodName: str) -> None:
        super().__init__(methodName=methodName)

then in the test file, instead of extending unittest.TestCase, do

from test import TestBase 

class Test_A(TestBase):
    ...