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
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 19486
Test Discovery fails with ModuleNotFoundError while command is working on console Β· Issue #19486 Β· microsoft/vscode-python
July 15, 2022 - Test discovery on the testing extension fails with ModuleNotFoundError: No module named 'mymodule' Manual run with pipenv run python3 -m pytest tests/test_*.py works well.
Author Β  dovahgab
Discussions

Test Discovery fails with E ModuleNotFoundError: No module named
Environment data Version: 1.42.0 Commit: ae08d5460b5a45169385ff3fd44208f431992451 Date: 2020-02-06T10:51:33.119Z Electron: 6.1.6 Chrome: 76.0.3809.146 Node.js: 12.4.0 V8: 7.6.303.31-electron.0 OS: ... More on github.com
🌐 github.com
12
February 9, 2020
python - VS Code Pytest Discovery Error Due to ModuleNotFoundError - Stack Overflow
I am trying to setup my VS Code debugger for pytest and am getting the error discovering pytests tests from the testing tab. The test I'm running works perfectly when run from the terminal but the VS More on stackoverflow.com
🌐 stackoverflow.com
how to set up pytest for subdirectory? Pytest Discovery Error
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) More on reddit.com
🌐 r/vscode
6
1
July 31, 2023
Pytest discovery stuck
[error] pytest test discovery error for workspace: /Users/zuk.bar/dev/gemini _pytest.nodes.Collector.CollectError: ImportError while importing test module '/Users/zuk.bar/dev/gemini/services/api/tests/test_api.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: ../../.pyenv/versions/3.10.12/lib/python3.10/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) E ModuleNotFoundError... More on github.com
🌐 github.com
4
April 26, 2024
🌐
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 β€Ί 10005
Test Discovery fails with E ModuleNotFoundError: No module named Β· Issue #10005 Β· microsoft/vscode-python
February 9, 2020 - python /<...>/ms-python.python-2020.1.58038/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir /path/to/root/of/project -s --cache-clear tests Β· Fails with "E ModuleNotFoundError: No module named 'mymodule'"
Author Β  zePanzerfaust
🌐
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": ["."],
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 23298
Pytest discovery stuck Β· Issue #23298 Β· microsoft/vscode-python
April 26, 2024 - [error] pytest test discovery error for workspace: /Users/zuk.bar/dev/gemini _pytest.nodes.Collector.CollectError: ImportError while importing test module '/Users/zuk.bar/dev/gemini/services/api/tests/test_api.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: ../../.pyenv/versions/3.10.12/lib/python3.10/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) E ModuleNotFoundError: No module named 'tests.test_api' Check Python Test Logs for more details.
Author Β  cliffqbio
Find elsewhere
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode β€Ί issues β€Ί 228248
Testing pytest discovery error Β· Issue #228248 Β· microsoft/vscode
September 11, 2024 - Data\Roaming\Python\Python39\s... ModuleNotFoundError: No module named 'werkzeug' 2024-09-11 17:25:20.852 [error] Subprocess exited unsuccessfully with exit code 1 and signal null on workspace c:\Users\jaesc2\GitHub\skforecast. 2024-09-11 17:25:20.852 [error] Subprocess exited unsuccessfully with exit code 1 and signal null on workspace c:\Users\jaesc2\GitHub\skforecast. Creating and sending error discovery payload 2024-09-11 17:25:20.852 [error] pytest test discovery ...
Author Β  JavierEscobarOrtiz
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 9450
Cannot discover with pytest in 2020-01 Β· Issue #9450 Β· microsoft/vscode-python
January 8, 2020 - Traceback (most recent call last): ...r\pytest\_discovery.py", line 8, in <module> import pytest ModuleNotFoundError: No module named 'pytest' with pytest installed in the base environment (using the base envornment or any other with pytest) I get the following error...
Author Β  CaselIT
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 25773
misidentifies pytest as not installed Β· Issue #25773 Β· microsoft/vscode-python
February 6, 2026 - return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ test_alice.py:3: in <module> import numpy as np E ModuleNotFoundError: No module named 'numpy' =========================== short test summary info ============================ ERROR test_alice.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! ===================== no tests collected, 1 error in 0.08s ===================== 2026-02-06 10:28:34.748 [error] pytest discovery failed with exit code 2 and signal null for workspace /Users/eleanorboyd/testing/tests-plus-projects/alice/bob.
Author Β  eleanorjboyd
🌐
Databricks
community.databricks.com β€Ί t5 β€Ί get-started-discussions β€Ί pytest-module-not-found-error β€Ί td-p β€Ί 113216
PYTEST: Module not found error - Databricks Community - 113216
November 12, 2025 - Code of exectest.ipynb file: ... ... named 'test_tran' when running pytest from a notebook is likely caused by how Python sets the module import paths and the current working directory inside Databricks notebooks (or similar environments)....
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 21757
Pytest Discovery Error Β· Issue #21757 Β· microsoft/vscode-python
August 4, 2023 - 2023-08-04 12:46:15.980 [error] pytest test discovery error [Error: spawn /opt/homebrew/bin/python3 ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (node:internal/child_process:506:16) at process.processTicksAndRejections (node:internal/process/task_queues:83:21)] { errno: -2, code: 'ENOENT', syscall: 'spawn /opt/homebrew/bin/python3', path: '/opt/homebrew/bin/python3', spawnargs: [ '-m', 'pytest', '-p', 'vscode_pytest', '--collect-only', 'tests' ] }
Author Β  alimbada
🌐
Reddit
reddit.com β€Ί r/vscode β€Ί cannot get pytest to work with vscode
r/vscode on Reddit: Cannot get pytest to work with VSCode
November 25, 2019 -

I am trying to get pytest to work. I am using VSCode, Anaconda and the Python extension on Windows 10 (all latest versions) with:

  • pytest 5.2.4.

  • Python 3.7

I am probably using the second most simplest use case. I have all my test files in a subdirectory called tests in the root directory of my application source code.

I can get test discovery and execution to work when I am at a command prompt with the activated anaconda environment and type: python -m . Pytest discovers all the tests and runs them with no problems whatsoever.

If I click on the Test discovery in VSCode, pytest finds all the test files but there are all kinds of ModuleNotFoundError errors. Example error output:

_____________________ ERROR collecting tests/test_acsr.py _____________________
ImportError while importing test module 'C:\path_to_source_code\tests\test_acsr.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\test_acsr.py:6: in <module>
    from acsr import is_pure_ground_run
E   ModuleNotFoundError: No module named 'acsr'

The acsr.py file is in the root of my application (parent directory of tests) and contains the functions I wish to test.

I checked the VS Code, and pytest documentation to see if I was missing some configuration options but didn't find anything. It appears that under VS Code, pytest can't figure out the sys.path or something. I feel like I am going around in circles trying to get this working as none of the answers on stackoverflow or anywhere else seem to fit this simple use case.

If anyone can supply me with a fix or has a link to a comprehensive tutorial that helps with pytest setup in VS Code I would be greatly appreciated.

PS I had it working in VS Code months ago, and I don't remember having to do any special configuration beyond what was outlined in the docs. It just stopped working one day, perhaps after an update, not sure. When it was working I thought it was pretty awesome.

🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί pytest can't locate my tests in my project structure after packaging the project
r/learnpython on Reddit: pytest can't locate my tests in my project structure after packaging the project
June 25, 2022 -

Hi there! πŸ‘‹

TL;DR

I am working on a project for a course I am doing. I am getting started with pytest so I can run tests against my code as I work on the project.

The project previously had a flat structure where the tests were in the same directory as the project scripts. That worked fine for me.

I have since restructured the code into what I understand is a better package structure so I can better present the project work in a repo that I created to showcase the project once I complete it.

The challenge now is that pytest can't locate my tests in VS Code (I'm using VS Code for my project partly because of the pytest support).

My project structure

This is my current project structure:

.
β”œβ”€β”€ README.md
β”œβ”€β”€ __pycache__
β”‚   β”œβ”€β”€ changeImage.cpython-39.pyc
β”‚   β”œβ”€β”€ process_data.cpython-39.pyc
β”‚   β”œβ”€β”€ run.cpython-39.pyc
β”‚   β”œβ”€β”€ supplier_image_upload.cpython-39.pyc
β”‚   β”œβ”€β”€ test_final_project.cpython-39-pytest-7.1.2.pyc
β”‚   β”œβ”€β”€ test_process_data.cpython-39-pytest-7.1.2.pyc
β”‚   └── upload_data.cpython-39.pyc
β”œβ”€β”€ catalog.egg-info
β”‚   β”œβ”€β”€ PKG-INFO
β”‚   β”œβ”€β”€ SOURCES.txt
β”‚   β”œβ”€β”€ dependency_links.txt
β”‚   └── top_level.txt
β”œβ”€β”€ environment.yml
β”œβ”€β”€ final_project
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ __pycache__
β”‚   β”‚   β”œβ”€β”€ __init__.cpython-39.pyc
β”‚   β”‚   β”œβ”€β”€ changeImage.cpython-39-pytest-7.1.2.pyc
β”‚   β”‚   β”œβ”€β”€ changeImage.cpython-39.pyc
β”‚   β”‚   └── supplier_image_upload.cpython-39.pyc
β”‚   β”œβ”€β”€ changeImage.py
β”‚   β”œβ”€β”€ emails.py
β”‚   β”œβ”€β”€ example_upload.py
β”‚   β”œβ”€β”€ report_email.py
β”‚   β”œβ”€β”€ reports.py
β”‚   β”œβ”€β”€ run.py
β”‚   β”œβ”€β”€ supplier-data
β”‚   β”‚   β”œβ”€β”€ descriptions
β”‚   β”‚   β”‚   β”œβ”€β”€ 001.txt
β”‚   β”‚   β”‚   β”œβ”€β”€ ...
β”‚   β”‚   └── images
β”‚   β”‚       β”œβ”€β”€ 001.jpeg
β”‚   β”‚       β”œβ”€β”€ 001.tiff
β”‚   β”‚       β”œβ”€β”€ 002....
β”‚   └── supplier_image_upload.py
β”œβ”€β”€ module_import.ipynb
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ setup.py
β”œβ”€β”€ supplier-data.tar.gz
└── tests
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ __pycache__
    β”‚   β”œβ”€β”€ __init__.cpython-39.pyc
    β”‚   └── test_final_project.cpython-39-pytest-7.1.2.pyc
    └── test_final_project.py

When I created the package, I used what I subsequently realised is a somewhat outdated method, here: https://calmcode.io/pytest/package.html.

I also tried running pip3 install -e . although I can't say I know what I'm really doing here. This is my first time structuring my projects like a grown-up.

My challenge

So my current challenge is that I see this output from pytest in VS Code when I try to discover my tests:

==================================== ERRORS ====================================
_________________ ERROR collecting tests/test_final_project.py _________________
ImportError while importing test module '/Users/pauljacobson/Git/Learn_to_code/giap-final-project/tests/test_final_project.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/miniconda3/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_final_project.py:6: in <module>
    from final_project.supplier_image_upload import list_supplier_data, upload_supplier_data
final_project/supplier_image_upload.py:4: in <module>
    from changeImage import list_images
E   ModuleNotFoundError: No module named 'changeImage'
=========================== short test summary info ============================
ERROR tests/test_final_project.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
===================== no tests collected, 1 error in 0.08s =====================

Traceback (most recent call last):
  File "/Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/get_output_via_markers.py", line 26, in <module>
    runpy.run_path(module, run_name="__main__")
  File "/opt/miniconda3/lib/python3.9/runpy.py", line 268, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "/opt/miniconda3/lib/python3.9/runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "/opt/miniconda3/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "/Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/adapter/__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "/Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 44, in discover
    raise Exception("pytest discovery failed (exit code {})".format(ec))
Exception: pytest discovery failed (exit code 2)
ERROR conda.cli.main_run:execute(49): `conda run python /Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/get_output_via_markers.py /Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir /Users/pauljacobson/Git/Learn_to_code/giap-final-project -s --cache-clear tests` failed. (See above for error)

    at ChildProcess.<anonymous> (/Users/pauljacobson/.vscode/extensions/ms-python.python-2022.8.0/out/client/extension.js:2:232793)
    at Object.onceWrapper (node:events:510:26)
    at ChildProcess.emit (node:events:390:28)
    at maybeClose (node:internal/child_process:1064:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)

When I configured pytest in VS Code, I selected pytest as the test framework, and the tests subdirectory as the location of my tests.

My question

So my question is how to make my tests discoverable here? My import statements in my test_final_project.py file are formatted like this:

from final_project.changeImage import list_images, reformat_images

If I "go to definition" for a module like changeImage, I am taken to the correct file.

What am I missing here?

Top answer
1 of 3
4
Hi there, calmcode author here :) I'm curious, what gives you the impression that the method is outdated? One thing that could be going awry is that you're using a `pytest` command that is not from your virtual environment. I've tried to explain the phenomenon in this virtualenv env on calmcode . The short anwer is to run `python -m pip install -e .` and to run `python -m pytest` instead. The video explains in more detail why. If you're curious about package development, you might appreciate the "building a python package" series where I document how I made a project from scratch. Granted, I'm not using the modern pyproject.toml approach, but it might be a helpful guide. The building a Python package series: - Part 1: Setup - Part 2: Tests - Part 3: Documentation
2 of 3
1
Unfortunately, I cannot read your code because of the formatting (old Reddit doesn't support triple ticks). But I think I know the problem. The problem is both with pytest and with how the majority of Python users (mis)understand how to work with packaging and how to test things. Here are conceptually different approaches to testing: Embed tests with the modules. I.e. the tests are then interspersed within the source code at every level of project hierarchy. This is the worst possible way to do this, nevertheless, it's very common. This requires running Python code from source directory instead from where it should be installed, and creates a lot of possibility for error when resolving resource files, dynamic libraries etc. Put tests in a separate directory alongside the project's root source directory. This is not as bad as (1), but it still ends up reading source code instead of installed code. So there's still a possibility for error discovering resources, but now, at least, all those errors will be consistent (because the source root is consistently in the same place). This is probably the most common way to do it. The right, and a very uncommon way to do it is to install your project prior to testing. On the face of it, there's a disadvantage: the project needs to be able to install in order to be tested, but, in practice, this is usually not an issue (unless you are working with Anaconda distribution of Python). This has a benefit however: all paths in your project will be resolved in the same way they would if installed by your user. So, if something doesn't work at this point: it's also broken for your users. Conversely, if you make it work within the confines of your environment, you get a much stronger guarantee that the project will work for your users as well. Independently of the above, it's almost universal in Python world, and almost universally wrong to distribute project tests with the distributable package. For example, NumPy does that and so do many others. This comes from sloppiness and misunderstanding of how things should work, just copying someone else's work, I guess. Ideally, and if you really want to distribute your project's tests, you should distribute them separately. And, if you really, really want that, you could make them a conditional dependency of your project, so that they can be installed via eg. pip install project[tests]. pytest, unfortunately, doesn't encourage to do things the right way, and, in fact, expects you to do things the wrong way. It will try to mess up your imports by manipulating them when running tests. In needs to be told explicitly to leave your imports alone, or you may even have to manage sys.path yourself just to avoid dealing with pytest nonsense. As a bottom line: Tests should import your code as if it was installed. You should, indeed install your code before running tests. Never run your tests from the root of your project. Or, preemptively, delete the current directory from the sys.path if you do that. The problem here is that unbeknownst to you, Python will load your source code instead of loading the installed code, and will lie to you (because it might succeed in such a way at loading resources / libraries, while the actual install will fail to do that). Optionally, make your tests into a separate package and install that for test purposes (but this is a lot of trouble for smaller packages). Your tests, documentation, and other utilities do belong in a source tarball, which is a different distribution method than Wheel or Egg. This method, however, shouldn't be relied on for installing packages for anything but development environment. Never in production environment. Unfortunately, pip and other PyPA tools betray you in this case too, and will happily install packages from source tarballs, causing many problems along the way both related to security and functionality your code.
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 22086
Pytest error: ModuleNotFoundError after updating to python 3.10 Β· Issue #22086 Β· microsoft/vscode-python
September 26, 2023 - Type: Bug Behaviour This is the error thrown after updating to python 3.10, with 3.7 worked just fine. Recreated settings.json with the extension but still got this error: 2023-09-26 11:46:30.920 [error] Error discovering pytest tests: [...
Author Β  rodzun
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 8896
pytest does not respect 'pytestPath' on test discovery Β· Issue #8896 Β· microsoft/vscode-python
December 4, 2019 - Reload and run pytest discovery. Should fail with: ModuleNotFoundError: No module named 'pytest'
Author Β  schperplata
🌐
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 - import pytest, report File "/home/cdsw/.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/adapter/pytest/init.py", line 7, in from ._discovery import discover File "/home/cdsw/.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 8, in import pytest ImportError: No module named pytest at ChildProcess.
Author Β  franva
🌐
Bobby Hadz
bobbyhadz.com β€Ί blog β€Ί python-no-module-named-pytest
ModuleNotFoundError: No module named 'pytest' in Python | bobbyhadz
April 8, 2024 - The Python "ModuleNotFoundError: No module named 'pytest'" occurs when we forget to install the pytest module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install pytest ...
🌐
GitHub
github.com β€Ί microsoft β€Ί vscode-python β€Ί issues β€Ί 19317
`python.testing.pytestPath` does not work with test discovery. Β· Issue #19317 Β· microsoft/vscode-python
June 16, 2022 - Traceback (most recent call last): File "/home/pc/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/run_adapter.py", line 17, in <module> from testing_tools.adapter.__main__ import parse_args, main File "/home/pc/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/adapter/__main__.py", line 9, in <module> from . import pytest, report File "/home/pc/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/adapter/pytest/__init__.py", line 7, in <module> from ._discovery import discover File "/home/pc/.vscode/extensions/ms-python.python-2022.8.0/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 8, in <module> import pytest ModuleNotFoundError: No module named 'pytest' This problem does get fixed if I install pytest into the relevant venv but I am wondering if there is a way around it.
Author Β  ProfessorCode212