ERROR: file not found when using pytest with VSCode (macOS)

Viewed 1359

I am trying to run a single unit test within VSCode by clicking Run Test (or Debug Test) above the unit test in the editor field, but I keep getting an ERROR: file not found:

============================= test session starts ==============================
platform darwin -- Python 3.8.8, pytest-4.6.11, py-1.10.0, pluggy-0.13.1
rootdir: <path_to_project_root>/module_1, inifile: /<path_to_project_root>/module_1/setup.cfg
plugins: cov-2.12.1, mock-1.13.0, xdist-1.34.0, forked-1.3.0
collected 0 items

- generated xml file: /var/folders/j9/lmgwz_dj4y97dx0zzf8kdgmc0000gn/T/tmp-1161ZMgD73kgVd4v.xml -
========================= no tests ran in 0.15 seconds =========================
ERROR: file not found: ./module_1/src/tests/pipelines/clean/test_cleaning.py::test_cleaning

I suspect that this can be due to the fact that the current working directory, (i.e. . in ERROR: file not found: ./) points to the <path_to_project_root>/module_1 instead of <path_to_project_root>, but if I change the cwd setting in settings.json, VSCode stops discovering my tests.

My directory tree looks like this:

project_root/
├─ module_1/
│  ├─ src/
│  │  ├─ tests/
│  ├─ setup.cfg
├─ module_2/

And some of (selected) settings defined in settings.json:

{
    "python.analysis.extraPaths": ["${workspaceFolder}/module_1/"],
    "python.autoComplete.extraPaths": ["${workspaceFolder}/module_1/"],
    "python.envFile": "${workspaceFolder}/.env",
    "python.testing.autoTestDiscoverOnSaveEnabled": true,
    "python.languageServer": "Pylance",
    "python.testing.cwd": "${workspaceFolder}/module_1",
    "python.testing.pytestArgs": ["--rootdir","${workspaceFolder}/module_1"],
    "python.testing.nosetestsEnabled": false,
    "python.testing.unittestEnabled": false,
    "python.testing.pytestEnabled": true
}

My .env file:

PYTHONPATH="<path_to_project_root>/module_1/src/"

My question is essentially: How can I resolve the ERROR: file not found error when running a single unit test in VSCode in such a (mono) repo?

Side/auxiliary questions:

  • How can I set the pytest current working directory to be <path_to_project_root> but still have VSCode discover my tests located inside <path_to_project_root>/module_1/src/?
  • Alternatively, how can I keep the cwd to be <path_to_project_root>/module_1 but tell VSCode not prepend a prefix /module_1/ when looking for tests?
  • How should settings.json look like to allow for seamless use of pytest inside the monorepo?
1 Answers

Although I have not found an answer on how to get rid of an error, I have found a workaround - Test Explorer UI plug-in is able to both: discover unit tests in a monorepo, and run them without failing with the aforementioned error.

Related