I spent ages trying to decipher this unhelpful error after creating a test that had import errors. Verify that your test suite can actually be executed before doing any deeper troubleshooting.

pytest --collect-only is your friend.

Answer from Autumn on Stack Overflow
🌐
Reddit
reddit.com › r/vscode › how to set up pytest for subdirectory? pytest discovery error
r/vscode on Reddit: how to set up pytest for subdirectory? Pytest Discovery Error
July 31, 2023 -

I am working on a data science project and my project tree looks like this:

data/
notebooks/
scripts/
utils/
- __init__.py
- utils1.py
- utils2.py
- utils3.py
- utils4.py
- tests/
-- test_utils1.py
-- test_utils2.py
-- test_utils3.py
-- test_utils4.py

I import functions I wrote in utils1.py, utils2.py, etc. to reuse throughout my notebooks and scripts. To run the tests for these, I cd into utils/ and then run python -m pytest from the terminal, which works fine.

I saw that there is a beaker icon for testing in VSCode, but my tests are not being discovered:

screenshot

Contents of __init__.py look a little like this:

from utils.utils4 import foo, barfrom .utils1 import foo2, bar2from .utils2 import function1, function2from .utils3 import *

See the comment below for Output.

It breaks my flow to switch to the terminal each time I modify a utility function to verify tests are passing. How should I configure VSCode to make better use of the Test Explorer?

Update: see my comment for the solution

Top answer
1 of 4
1
2023-07-26 15:21:31.015 [info] Discover tests for workspace name: project-name-here - uri: /Users/username/repos/project-name-here 2023-07-26 15:21:31.020 [info] > /opt/homebrew/bin/python3.11 ~/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir ./utils/tests/ -s --cache-clear . 2023-07-26 15:21:31.020 [info] cwd: ./utils/tests/ 2023-07-26 15:21:31.214 [error] Error discovering pytest tests: n [Error]: ============================= test session starts ============================== platform darwin -- Python 3.11.0, pytest-7.3.2, pluggy-1.0.0 rootdir: /Users/username/repos/project-name-here/utils/tests plugins: anyio-3.6.2 collected 0 items / 4 errors ==================================== ERRORS ==================================== ___________________ ERROR collecting test_utils1.py ____________________ ImportError while importing test module '/Users/username/repos/project-name-here/utils/tests/test_utils1.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) ../__init__.py:5: in from .utils2 import function1, function2 ../utils2.py:26: in from numpy import array as np_array E ModuleNotFoundError: No module named 'numpy' ____________________ ERROR collecting test_utils2.py _____________________ ImportError while importing test module '/Users/username/repos/project-name-here/utils/tests/test_utils2.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) ../__init__.py:5: in from .utils2 import function1, function2 ../utils2.py:26: in from numpy import array as np_array E ModuleNotFoundError: No module named 'numpy' _____________________ ERROR collecting test_utils3.py ______________________ ImportError while importing test module '/Users/username/repos/project-name-here/utils/tests/test_utils3.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) ../__init__.py:5: in from .utils2 import function1, function2 ../utils2.py:26: in from numpy import array as np_array E ModuleNotFoundError: No module named 'numpy' ________________________ ERROR collecting test_utils4.py ________________________ ImportError while importing test module '/Users/username/repos/project-name-here/utils/tests/test_utils4.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) ../__init__.py:5: in from .utils2 import function1, function2 ../utils2.py:26: in from numpy import array as np_array E ModuleNotFoundError: No module named 'numpy' =========================== short test summary info ============================ ERROR test_utils1.py ERROR test_utils2.py ERROR test_utils3.py ERROR test_utils4.py !!!!!!!!!!!!!!!!!!! Interrupted: 4 errors during collection !!!!!!!!!!!!!!!!!!!! ==================== no tests collected, 4 errors in 0.04s ===================== Traceback (most recent call last): File "/Users/username/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/testing_tools/run_adapter.py", line 22, in main(tool, cmd, subargs, toolargs) File "/Users/username/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/testing_tools/adapter/__main__.py", line 99, in main parents, result = run(toolargs, **subargs) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/username/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 47, in discover raise Exception("pytest discovery failed (exit code {})".format(ec)) Exception: pytest discovery failed (exit code 2) at ChildProcess. (/Users/username/.vscode/extensions/ms-python.python-2023.12.0/out/client/extension.js:2:241817) at Object.onceWrapper (node:events:628:26) at ChildProcess.emit (node:events:513:28) at maybeClose (node:internal/child_process:1121:16) at Socket. (node:internal/child_process:479:11) at Socket.emit (node:events:513:28) at Pipe. (node:net:757:14)
2 of 4
1
Here's what I did to fix my pytest config: selected the desired Python interpreter based on my virtual environment using the Command Palette (Python: Select Interpreter) added __init__.py to utils/tests/ In the tests/test_utils#.py files, I was previously importing like from .utils# import foo, bar but I changed it to from utils.utils# import foo, bar verified that my workspace settings had the following lines:"python.testing.unittestEnabled": false,"python.testing.pytestEnabled": true,"python.testing.pytestArgs": ["."],
Discussions

Python Test Discovery Failed with no error message
Issue Type: Bug I tried to run "Python: Discover Tests" but I got a message saying "Test discovery failed". I don't see any other information about what the failure was (for example no text is writ... More on github.com
🌐 github.com
34
April 30, 2020
Test discovery error with pytest
Tests can be ran from the command line with success using pytest directly with no errors, however test discovery in vscode fails with error: More on github.com
🌐 github.com
7
March 18, 2020
Pytest discovery fails
Type: Bug Behaviour Expected vs. Actual I expect discovery to work, for the explorer to populate with tests. Instead I get pytest discovery error (see Output > Python) Steps to reproduce: Click ... More on github.com
🌐 github.com
13
July 6, 2023
VSCode cannot detect pytest unit tests, even pytest has been installed, error comes from inside .vscode-serve folder, behind company's proxy
VSCode cannot detect pytest unit ... inside .vscode-serve folder, behind company's proxy#19556 ... area-environmentsFeatures relating to handling interpreter environmentsFeatures relating to handling interpreter environmentsarea-testingbugIssue identified by VS Code Team member as probable bugIssue identified by VS Code Team member as probable bugverifiedVerification succeededVerification succeeded ... Expect a list of unit tests, actually got the error message: Error discovering pytest tests (see ... More on github.com
🌐 github.com
15
July 26, 2022
🌐
GitHub
github.com › microsoft › vscode-python › issues › 21757
Pytest Discovery Error · Issue #21757 · microsoft/vscode-python
August 4, 2023 - Type: Bug Behaviour Expected vs. Actual Expected: Discover, run and debug tests Actual: Python3 error (see output from Output panel below). Steps to reproduce: Try to discover/run/debug tests Everything works fine from the terminal using...
Author   alimbada
🌐
GitHub
github.com › microsoft › vscode-python › issues › 11513
Python Test Discovery Failed with no error message · Issue #11513 · microsoft/vscode-python
April 30, 2020 - Issue Type: Bug I tried to run "Python: Discover Tests" but I got a message saying "Test discovery failed". I don't see any other information about what the failure was (for example no text is written to my terminal). According to the Py...
Author   juliussimonelli
🌐
GitHub
github.com › microsoft › vscode-python › issues › 10636
Test discovery error with pytest · Issue #10636 · microsoft/vscode-python
March 18, 2020 - Tests can be ran from the command line with success using pytest directly with no errors, however test discovery in vscode fails with error:
Author   mblackgeo
🌐
GitHub
github.com › microsoft › vscode-python › issues › 21576
Pytest discovery fails · Issue #21576 · microsoft/vscode-python
July 6, 2023 - Type: Bug Behaviour Expected vs. Actual I expect discovery to work, for the explorer to populate with tests. Instead I get pytest discovery error (see Output > Python) Steps to reproduce: Click the 'refresh tests' button on the testing p...
Author   kjohnsen
🌐
GitHub
github.com › microsoft › vscode-python › issues › 19556
VSCode cannot detect pytest unit tests, even pytest has been installed, error comes from inside .vscode-serve folder, behind company's proxy · Issue #19556 · microsoft/vscode-python
July 26, 2022 - VSCode cannot detect pytest unit tests, even pytest has been installed, error comes from inside .vscode-serve folder, behind company's proxy#19556 ... area-environmentsFeatures relating to handling interpreter environmentsFeatures relating to handling interpreter environmentsarea-testingbugIssue identified by VS Code Team member as probable bugIssue identified by VS Code Team member as probable bugverifiedVerification succeededVerification succeeded ... Expect a list of unit tests, actually got the error message: Error discovering pytest tests (see Output > Python):
Author   franva
Find elsewhere
🌐
GitHub
github.com › microsoft › vscode-python › issues › 19809
pytest discovery error · Issue #19809 · microsoft/vscode-python
September 10, 2022 - Type: Bug error discovering pytest tests Extension version: 2022.14.0 VS Code version: Code 1.70.2 (Universal) (e4503b30fc78200f846c62cf8091b76ff5547662, 2022-08-16T05:36:37.829Z) OS version: Darwi...
Author   stanezeaku
🌐
GitHub
github.com › microsoft › vscode-python › issues › 18431
Pytest discovery fails if something is printed to stderr · Issue #18431 · microsoft/vscode-python
February 3, 2022 - microsoft / vscode-python Public forked from DonJayamanne/pythonVSCode · Notifications · You must be signed in to change notification settings · Fork 1.3k · Star 4.6k · New issueCopy link · New issueCopy link · Closed · Closed · Pytest discovery fails if something is printed to stderr#18431 ·
Author   1st
🌐
GitHub
github.com › microsoft › vscode-python › issues › 15314
VSCode test discovery fails while looking for non-existent file or directory · Issue #15314 · microsoft/vscode-python
April 2, 2021 - python /Users/electronhead/.vscode/extensions/ms-python.python-2021.1.502429796/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir /Users/electronhead/dev/pyrambium -s --cache-clear base Test Discovery failed: Error: ============================= test session starts ============================== platform darwin -- Python 3.9.0, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 rootdir: /Users/electronhead/dev/pyrambium plugins: asyncio-0.14.0 collected 0 items ========================= no tests collected in 0.01s ========================== ERROR: file or directory not found: base Trac
Author   electronhead
🌐
GitHub
github.com › microsoft › vscode-python › issues › 5494
PyTest Fails to Discover if VSCode believes code is bad even if its not · Issue #5494 · microsoft/vscode-python
April 26, 2019 - Relevant/affected Python packages and their versions: PyTest 4.1 · Expected: Find all unit tests and run them regardless of if VSCode thinks they work or not. Actual: Test discovery fails if VS Code beleives there is a problem in any test file be it a real problem or not or if it is 1 test of 1,000 or 999 of 1,000.
Author   drcrook1
🌐
GitHub
github.com › microsoft › vscode-python › issues › 22513
VSCode Pytest Discovery Fails With Unhelpful Error · Issue #22513 · microsoft/vscode-python
November 21, 2023 - Originally posted by dylan-at-na November 17, 2023 PyTest Discovery consistently failing, the error message isn't telling me much. Error messages follow (full log at end of message). The Python extension has run into an unexpected situation while processing a pytest node during test discovery. Please Please open an issue at: https://github.com/microsoft/vscode-python/issues and paste the following output there.
Author   brettcannon
🌐
GitHub
github.com › microsoft › vscode-python › issues › 18045
Error discovering pytest tests · Issue #18045 · microsoft/vscode-python
November 16, 2021 - Tests are properly discovered. ... { "python.testing.pytestArgs": [ "server/src" ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "python.linting.enabled": true } ... > ~/dev/second/server/.venv/bin/python ~/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir ~/dev/second -s --cache-clear server/src cwd: ~/dev/second Error 2021-11-16 23:44:18: Error discovering pytest tests: r [Error]: ============================= test session starts ============================== platform darwin -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 rootdir: /Users/rbhalla/dev/second plugins: pspec-0.0.4, mock-3.6.1, anyio-3.3.4 The Python extension has run into an unexpected situation while processing a pytest node during test discovery.
Author   rbhalla
🌐
GitHub
github.com › microsoft › vscode-python › issues › 24127
pytest discovery fails with ModuleNotFound · Issue #24127 · microsoft/vscode-python
September 18, 2024 - Type: Bug Behaviour pytest discovery fails with a ModuleNotFoundError, when the module is clearly installed in my environment Steps to reproduce: Import non-standard package (but one that is installed in the environment) in tests/conftes...
Author   kjohnsen
🌐
GitHub
github.com › microsoft › vscode-python › issues › 6417
Test discovery failed for pytest 4.3.0 (not including cwd in path) · Issue #6417 · microsoft/vscode-python
July 2, 2019 - python C:\Users\kanadig\.vscode\extensions\ms-python.python-2019.6.22090\pythonFiles\testing_tools\run_adapter.py discover pytest -- -s --cache-clear Test Discovery failed: Error: I+00.047: Test environment: CPU count: 12 System paths: sys.prefix: C:\Python37 sys.base_prefix: C:\Python37 sys.real_prefix: <missing> site.getsitepackages(): C:\Python37 C:\Python37\lib\site-packages site.getusersitepackages(): C:\Users\kanadig\AppData\Roaming\Python\Python37\site-packages sys.path (site-packages): C:\Python37\lib\site-packages C:\Users\kanadig\AppData\Roaming\Python\Python37\site-packages sysconfi
Author   karthiknadig
🌐
CSDN
devpress.csdn.net › python › 63044eefc67703293080abdf.html
VSCode pytest test discovery fails - DevPress官方社区- CSDN
August 23, 2022 - Answer a question Pytest test discovery is failing. The UI states: Test discovery error, please check the configuration settings for the tests The output window states: Test Discovery failed: Error: T Mangs Python
🌐
GitHub
github.com › microsoft › vscode-python › issues › 23298
Pytest discovery stuck · Issue #23298 · microsoft/vscode-python
April 26, 2024 - Type: Bug Behaviour running tests discovery fails Steps to reproduce: have settings.json with: { "python.testing.pytestArgs": [ "--no-cov", "./services/sys/tests/", "./services/api/tests/", ], "python.testing.autoTestDiscoverOnSaveEnable...
Author   cliffqbio
🌐
Reddit
reddit.com › r/vscode › why is test discovery failing?
r/vscode on Reddit: Why is test discovery failing?
March 10, 2021 -

pytest works from the command line, therefore it is installed correctly (I use Anaconda). But within VS Code I simply cannot get it to work. In the log, I get this error:

python c:\Users\renan\.vscode\extensions\ms-python.python-2021.2.636928669\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir c:\Users\renan\Documents\Sources\Python-6502 -s --cache-clear
Test Discovery failed: 
TypeError: Cannot read property 'uri' of undefined

My settings.json is:

{
    "python.testing.cwd": ".",
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.pythonPath": "C:\\ProgramData\\Anaconda3\\python.exe"
}

Python version is 3.8.5, I am using the Python extension from the repo and my VSCode version is:

Version: 1.54.1 (user setup)
Commit: f30a9b73e8ffc278e71575118b6bf568f04587c8
Date: 2021-03-04T22:38:31.419Z (5 days ago)
Electron: 11.3.0
Chrome: 87.0.4280.141
Node.js: 12.18.3
V8: 8.7.220.31-electron.0
OS: Windows_NT x64 10.0.19042

What am I missing?

🌐
GitHub
github.com › microsoft › vscode-python › issues › 24632
pytest discovery never ends · Issue #24632 · microsoft/vscode-python
December 17, 2024 - Type: Bug Behaviour When I click on the the "test explorer" UI icon, in order to trigger discovery of python tests in my projects (I am using a multi-root workspace), it shows like it starting, but never ends. No clear errors in the pyth...
Author   Imanuel-Miz