Search code examples
pythonvisual-studio-code

Is there a way to configure VSCode to discover Python test files under a subdirectory?


I have a project containing a Python backend and a React frontend. So my file/folder structure looks something like this:

.
├── backend
│   ├── mypackage
│   │   └── main.py
│   ├── tests
│   │   └── test_main.py
│   ├── Dockerfile
│   └── pyproject.toml
├── frontend
│   ├── src
│   │   └── App.js
│   ├── Dockerfile
│   └── package.json
└── README.md

And my test file contains code like this:

from mypackage.main import my_function

def test_that_my_function_works():
    my_function()

When I click on the Testing tab in VSCode, I get a pytest Discovery Error, and digging into the logs shows this:

ImportError while importing test module '/home/user/myproject/backend/tests/test_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../../.pyenv/versions/3.12.1/lib/python3.12/importlib/__init__.py:90: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
backend/tests/test_main.py:1: in <module>
    from mypackage.main import my_function
E   ModuleNotFoundError: No module named 'mypackage'
=========================== short test summary info ============================
ERROR backend/tests/test_main.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
===================== no tests collected, 1 error in 0.17s =====================

It seems Visual Studio Code is treating the root of the repository as the base of where to run pytest, when really I want it to only focus on what's in the backend/ folder. How can I achieve this?


Solution

  • You could try to modify your settings.json:

    {
        "python.testing.pytestArgs": [
            "backend" //set the entry to specify the backend directory as the root for pytest
        ],
        "python.testing.unittestEnabled": false,
        "python.testing.pytestEnabled": true,
        "python.envFile": "${workspaceFolder}/.env",
    }
    

    At the same time, ensure that the PYTHONPATH environment variable includes the backend directory. You could set this in your .env file in the root of your project.

    PYTHONPATH=backend