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
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
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
๐ŸŒ
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 โ€บ 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
๐ŸŒ
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
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
๐ŸŒ
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 โ€บ 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
๐ŸŒ
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