You could select your python interpreter in VSCode by shortcuts "Ctrl+Shift+P" and type "Python: Select Interpreter" and choose the python interpreter which you installed the package in.

If it still not work, you could run command pip install pytest in the terminal to install the package in the current interpreter.

Answer from MingJie-MSFT on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › vscode and pytest not recognizing imports
r/learnpython on Reddit: VSCode and pytest not recognizing imports
April 19, 2025 -

So I'm migrating my code to a new project format after learning about how they should be formatted for release. I'm using UV to create the .git-ignore and all the other goodies it does. The package is called cmo. I'm trying to run tests on some of the code and resolve imports.

So as an example: I have cmo/src/data/doctrine/air_operations_tempo. And I have a file cmo/src/helpers/values/get_item_from_menu with the function get_item_from_menu.

air_operations_tempo imports it but is getting an error that neither com/src/etc. nor src/helpers/etc. work as a valid import path.

Also, trying to import air_operations_tempo into cmo/tests/data/doctrine/test_air_operations_tempo doesn't work either with cmo/src/etc. nor src/data/etc.

I am at a loss it works on the old code but not anymore. Any help would be GREATLY appreciated. I am at wits end. It's probably something simple knowing my luck.

A picture of the file structure

🌐
Stack Exchange
devops.stackexchange.com › questions › 16370 › vscode-pytest-gives-me-an-error-when-importing
python - Vscode/pytest gives me an error when importing - DevOps Stack Exchange
I asked this question on the regular stackoverflow but i think you guys will be much more competent about this topic. My guess is that is some sort of python setup issue. When I write an import line like this from mypackage import something and run it using vscode tools it gives my an error, when I run it using venv python it works. Same for pytest, I have to run it like this: python3 -m pytest tests for it to work.
🌐
Reddit
reddit.com › r/learnpython › can't import pytest_bdd
r/learnpython on Reddit: Can't import pytest_bdd
June 23, 2021 -

I am unable to import pytest_bdd by following all the guides.

I am using the line

from pytest_bdd import scenario, given, when, then, parsers

in my Project/tests/step_defs/GUI_step_defs.py

I get: 'Import "pytest_bdd" could not be resolved'

Any tips?

Info:

Vs code (IDE and pytest_bdd extention)

Top answer
1 of 15
2

Kept everything same and just added a blank test file at the root folder .. Solved it

Here are the findings, this problem really bugged me for a while. My folder structure was

mathapp/
    - server.py  
    - configuration.py 
    - __init__.py 
    - static/ 
       - home.html  
tests/            
    - functional 
       - test_errors.py 
    - unit  
       - test_add.py

and pytest would complain with the ModuleNotFoundError and gives the hint:

make sure your test modules/packages have valid Python names.

I introduced a mock test file at the same level as mathsapp and tests directory. The file contained nothing. Now pytest does not complain.

Result without the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 1 item / 1 error

=================================== ERRORS ====================================
_______________ ERROR collecting tests/functional/test_func.py ________________
ImportError while importing test module 'C:\mainak\workspace\0github\python-rest-app-cont\tests\functional\test_func.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\functional\test_func.py:4: in <module>
    from mathapp.service import sum
E   ModuleNotFoundError: No module named 'mathapp'
=========================== short test summary info ===========================
ERROR tests/functional/test_func.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
============================== 1 error in 0.24s ===============================

Results with the file

$ pytest
============================= test session starts =============================
platform win32 -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\mak2006\workspace\0github\python-rest-app-cont
collected 2 items

tests\functional\test_func.py .                                          [ 50%]
tests\unit\test_unit.py .                                                [100%]

============================== 2 passed in 0.11s ==============================
2 of 15
2

update PYTHONPATH till src folder

export PYTHONPATH=/tmp/pycharm_project_968/src
🌐
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.

Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › python-no-module-named-pytest
ModuleNotFoundError: No module named 'pytest' in Python | bobbyhadz
April 8, 2024 - To solve the error, install the module by running the pip install pytest command. Open your terminal in your project's root directory and install the pytest package. ... Copied!# 👇️ In a virtual environment or using Python 2 pip install ...
🌐
GitHub
github.com › microsoft › pylance-release › issues › 1020
Installed packaged not being 'resolved' - Brownie and PyTest · Issue #1020 · microsoft/pylance-release
March 7, 2021 - import brownie from brownie import accounts, Farm import pytest pylance doesn't recognize these libraries though the warning is ignored and compiles correctly as these are all up to date on my ...
Author   liam-ot
🌐
GitHub
github.com › microsoft › pyright › discussions › 8847
Warning on pytest import · microsoft/pyright · Discussion #8847
Please reload this page. ... If you set the "verboseOutput" config setting to true, you should see a bunch of additional logging output that may help you diagnose the import resolution issue. Beta Was this translation helpful?
Author   microsoft
🌐
freeCodeCamp
forum.freecodecamp.org › python
Pytest Installed, but VS Code Won't Access Pytest - Python - The freeCodeCamp Forum
September 12, 2023 - Hi, I’m starting to learn how to write tests for my code. I’ve installed pytest on my device using pip. But VS Code won’t access it. I assume it’s something to do with the path. I’ve tried using different IDEs, but I can’t find one that will let me use pytest without installing it.
🌐
Reddit
reddit.com › r/learnpython › pytest import errors
r/learnpython on Reddit: pytest Import Errors
May 24, 2020 -

** EDIT **

This is fixed now. There was a conflict when running imports. Within my internet_speed_tester directory because my main file was called internet_speed_tester.py and matched the main package file name as well, when running imports, they were trying to import from this file instead of the package itself.

Renaming internet_speed_tester_.py to main.py resolved this.

With the project installed to my virtual environment with pip install -e ., imports are working as expected now with the following syntax being used in both tests and package files, no messing about with sys.path:

from internet_speed_tester.misc_functions import print_msg

pytest -v also works as expected from the root directory.

** Original Post **

I'm running into some errors with imports on pytest.

I thought this was possible without mucking around with sys.path in each file if you were to install the project to your environment with pip install -e . but I can't seem to get this working.

My goal is to be able to run something like pytest -v from my tests root directory and have it iterate through each of my test files. I've installed the project to my virtual environment with pip install -e .

Here's the project layout:

internet_speed_tester:
|
|   setup.py
|   
+---internet_speed_tester
|   |
|   |   internet_speed_tester.py
|   |   __init__.py
|   |   
|   +---misc_functions
|   |   |   check_arguments.py
|   |   |   output_progress.py
|   |   |   print_msg.py
|   |   |   set_logname.py
|   |   \---__init__.py
|   |           
|   +---registry_functions
|   |   |   config_registry.py
|   |   |   query_registry.py
|   |   |   set_registry.py
|   |   \---__init__.py
|   |           
|   +---site_connection_functions
|       |   validate_site_connection.py
|       \---__init__.py
|       
+---tests
    |   .coverage
    |   conftest.py
    |   
    +---integration
    |   |   test_output_progress.py
    |   |   test_print_msg.py
    |   \---test_validate_site_connection.py
    |           
    +---unit
        |   test_check_arguments.py
        |   test_query_registry.py
        \---test_set_logname.py

The main error pytest is throwing is which comes up :

..\internet_speed_tester\site_connection_functions\validate_site_connection.py:10: in <module>
    from misc_functions import output_progress
E   ModuleNotFoundError: No module named 'misc_functions'

Here's some snippets from the related files to the error above:

# internet_speed_tester\setup.py

from setuptools import find_packages, setup

setup(

    name='internet_speed_tester',
    version='0.5',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,

)

Examples of imports:

# internet_speed_tester\validate_site_connection.py

from misc_functions import output_progress

# internet_speed_tester\misc_functions\__init__.py

from .check_arguments import check_arguments
from .print_msg import print_msg
from .output_progress import write_log, output_progress
from .set_logname import set_logname

# tests\integration\test_validate_site_connection.py

from internet_speed_tester.site_connection_functions import validate_site_connection

My internet_speed_tester\__init__.py file is blank.

I can run python .\internet_speed_tester.py without errors currently, but pytest -v from the tests directory throws the error above. Would really appreciate any insights, I feel like I'm close.

🌐
Finxter
blog.finxter.com › home › learn python blog › [fixed] no module named ‘pytest’
[Fixed] No module named 'pytest' - Be on the Right Side of Change
August 24, 2023 - The most likely reason is that Python doesn’t provide pytest in its standard library. You need to install it first! Before being able to import the Pandas module, you need to install it using Python’s package manager pip.
🌐
Python Forum
python-forum.io › thread-40713.html
Pytest Installed, but VS Code Won’t Access Pytest
September 12, 2023 - Hi, Sorry, I understand questions about installing packages and problems with path directories are common, but I've tried everything and really need help. I’m starting to learn how to write tests for my code. I’ve installed pytest on my device...
🌐
Reddit
reddit.com › r/learnpython › my pytest code doesn't find my code
r/learnpython on Reddit: My Pytest code doesn't find my code
March 14, 2023 -

I'm writing simple code to learn Python, and I thought I would use TDD as I wrote it. (I have programmed in other languages such as Ruby.) I am trying to build good habits and to use best practices, but I'm having trouble with Pytest discovering my code.

Here's the structure of my example project:

├── venv
├── tests
│   ├── test_myclass.py
├── src
│   └── demo
│       ├── __init__.py
│       └── my_class.py
└── setup.py

Here's the contents of the files:

setup.py

from setuptools import setup, find_packages

setup(name="demo", packages=find_packages())

src/demo/my_class.py

class MyClass:

    def hello(self):
        return "hello"

src/demo/__init__.py is empty.

tests/test_myclass.py

class TestMyClass:

    def test_hello(self):
        my_class = MyClass()
        assert(my_class.hello() == "hello")

When I run pytest from the top-level of my example repo, I get this:

============================= test session starts ==============================
platform darwin -- Python 3.10.10, pytest-7.2.2, pluggy-1.0.0
rootdir: /Users/me/src/python/venv_projects/repo
collected 1 item

tests/test_myclass.py F                                                  [100%]

=================================== FAILURES ===================================
____________________________ TestMyClass.test_hello ____________________________

self = <test_myclass.TestMyClass object at 0x10c3e8190>

    def test_hello(self):
>       my_class = MyClass()
E       NameError: name 'MyClass' is not defined

tests/test_myclass.py:4: NameError
=========================== short test summary info ============================
FAILED tests/test_myclass.py::TestMyClass::test_hello - NameError: name 'MyClass' is not defined
============================== 1 failed in 0.07s ===============================

I'm clearly missing the right way to get Pytest to discover the class to test. I tried putting in an import demo statement in TestMyClass, but that didn't help the situation.

I did read that I could tinker with sys.path or PYTHONPATH, but those approaches seemed to be a bit hack-y, and not representative of best practices.

What should I do to get my test to pass here?

Thank you!

🌐
Reddit
reddit.com › r/learnpython › pytest mysteriously ignores changes to imported code. why?!!
r/learnpython on Reddit: Pytest mysteriously ignores changes to imported code. Why?!!
October 4, 2024 -

Once I run pytest it won't acknowledge any further code changes to the Python module it's importing to test.

What I'm specifically doing is adding a print statement in one of my functions then I run pytest -s to show any output, and what I observe is that pytest ignores any addition or removal of print() statements from the originally run version of the module.

I can only get it to work if I git clone my project into a new directory but after running pytest once there I get the same problem.

Is there a configuration I've messed up somewhere in pytest.ini or conftest.py?

Please someone help me find out what is going on!

GitHub Repo: https://github.com/alexcwarren/replace-template

EDIT: For further clarity, I'm running on Windows 11, Python v3.10.5 (using pyenv for Python version management) inside a venv virtual environment. I've tried running the pytest command in VSCode and in a separate PowerShell terminal.

SOLVED: The solution was I needed to run pip install . again after making changes to my local Python code (since it’s structured as a Python package). I could also supposedly initially install everything in editable mode, i.e. pip install -e ., and that would allow pytest to use local code changes instead of only installed versions of local code.

🌐
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 - Your issue with ModuleNotFoundError: No module 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). This is different from a traditional shell ...