PATH issue with pytest 'ImportError: No module named YadaYadaYada'

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so:

repo/ repo/app.py repo/settings.py repo/models.py repo/tests/ repo/tests/test_app.py 

run py.test while in the repo directory, everything behaves as you would expect

but when I try that same thing on either linux or windows (both have pytest 2.2.3 on them) it barks whenever it hits its first import of something from my application path. Say for instance from app import some_def_in_app

Do I need to be editing my PATH to run py.test on these systems? Has Anyone experienced this?

回答1:

yes, the source folder is not in python's path if you cd to the tests directory. you have 2 choices:

a. Add the path manually to the test files, something like:

import sys, os myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../') 

b. run the tests with the env var PYTHONPATH=../.



回答2:

I'm not sure why py.test does not add the current directory in the PYTHONPATH itself, but here's a workaround (to be executed from the root of your repository):

python -m pytest tests/ 

It works because Python adds the current directory in the PYTHONPATH for you.



回答3:

I had the same problem. I fixed it by adding an empty __init__.py file to my tests directory.



回答4:

You can run with PYTHONPATH in project root

PYTHONPATH=. py.test 

Or use pip install as editable import

pip install -e .   # install package using setup.py in editable mode 


回答5:

I created this as an answer to your question and my own confusion. I hope it helps. Pay attention to PYTHONPATH in both the py.test command line and in the tox.ini.

https://github.com/jeffmacdonald/pytest_test

Specifically: You have to tell py.test and tox where to find the modules you are including.

With py.test you can do this:

PYTHONPATH=. py.test 

And with tox, add this to your tox.ini:

[testenv] deps= -r{toxinidir}/requirements.txt commands=py.test setenv =     PYTHONPATH = {toxinidir} 


回答6:

Run pytest itself as a module with: python -m pytest tests



回答7:

I started getting weird "ConftestImportFailure: ImportError('No module named ..." errors when I had accidentally added __init__.py file to my src directory (which was not supposed to be a Python package, just a container of all source).



回答8:

I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.

'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!