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.
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
Videos
This is by far the weirdest error i've ever seen. I won't bother with code cause it's easier with a screenshot IMO
I've tried it with multiple iterations (my_weather vs weather or w_eather vs weather) and somehow after trying a gazilliion things (you can see in my console how many times i've tried adding the PYTHONPATH) the only things that matters is... an underscore?
Please tell me whats up so I can go to sleep tonight.
probably Pylance is having problems with the path for site-packages folder for your virtual environment and returns Import "pytest" could not be resolved, you need to set python path in this way:
"python.pythonPath": "/my/project/path/.venv/bin/python"
I tried h. deville fletcher's answer and it didn't seem to work for me, but I could have messed up in there too. However, in the process, I remembered that I hadn't changed my interpreter. Once I changed the interpreter to my pipenv shell that fixed my problem.
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)
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 ==============================
update PYTHONPATH till src folder
export PYTHONPATH=/tmp/pycharm_project_968/src
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.
I'm currently learning python and trying to import a module into my actual file. My code runs as its supposed to, but I keep getting this error message / warning. The module and the actual file are both in the same directory, and my Editor is vscode. I really appreciate any help, thanks in advance.
I have a project with a structure like this:
MyProject/ my_module/ __init__.py asd1/ __init__.py asd2/ __init__.py tests/ my_module_tests.py
I wanted to create tests but when I try to import my functions/classes I got an import error when I run pytest inside my project.
The funny thing is, that when I just wrote a simple 2 line script with my imports and I ran python asd_test.py (This was inside the tests folder too) I didn't get any import error.
Why is that and how can I fix this?
** 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.pyThe 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.
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!
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.