I have a project where I want to VS Code's discover tests and other testing features to make testing easier. I have a problem that imports in test files break when I try to discover tests.
I have a file structure like so:
project\
__init__.py
package1\
module1.py
__init__.py
tests\
test.py
__init__.py
In test.py I have a line:
import project.package1.module1 as module1
I run my project by calling python -m project
in the root folder, and I am able to run tests successfully by calling python -m pytest project
from the root folder.
When I run VS Code's "discover tests" feature or try to step through a file with the debugger, I receive an error 'ModuleNotFoundError: No module named project'.
Does anyone know how to solve this problem?
"name": "Python: Module",
configuration set in yourlaunch.json
(the gear icon in Debug pane)? Did you set the correct interpreter? – Coastguardsmanenter-your-module-name-here
toproject
, save the json and you're good to go. – Coastguardsmanproject/
directory in VS Code or the parent directory ofproject/
? P.S.: you can simplify that import statement asfrom project.package1 import module1
. – Heraclesenter-your-module-name-here
did not work. I have opened the parent directory ofproject/
in vscode as this is where the venv and other files live. – Galactopoietic__main__.py
file next to package's__init__.py
withif __name__ == "__main__":
in it. When you say you run your program withpython -m project
, what function is been called that way? – Coastguardsman__main__.py
in andapp.py
inpackage`. In
__main__.py` isfrom project import app
andif __name__ == "__main__": app.run()
. – Galactopoieticsys.path
to see where Python is looking for modules to help understand why Python can't findproject
. – Heraclespython -m project
and I can test fine withpython -m pytest project
or evenpython -m pytest project\tests\test.py
. When I dopython
and thenimport sys
,sys.path
I get['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/dan/Documents/.../Project/venv/lib/python3.7/site-packages']
whereProject
is the parent folder ofproject
– Galactopoieticsys.path
. I am not a Python expert and the import system is very complicated – Galactopoieticimport os; print(os.getcwd())
print out'/home/dan/Documents/.../Project'
for''
. You don't have an__init__.py
inProject/
do you? That has been known to mess things up before. We also have a fix for some test discovery in the next release you can test by installing the development build of the extension. Otherwise we are at the point that you will need to open an issue at github.com/microsoft/vscode-python. – Heracles/home/.../Project' from
getcwd()` and there is no__init__.py
in Project. Thank you for the help. – Galactopoietic