[英]ImportError: No module named requests in 'pytest'
root
| +-- demo
|-->__init__.py
|-->conftest.py
|-->test.py
conftest.py
import pytest
def tear_down():
print "\nTEARDOWN after all tests"
@pytest.fixture(autouse=True)
def set_up(request):
print "\nSETUP before all tests"
if request.cls.__name__ == 'TestClassA':
return ["username", "password"]
request.addfinalizer(tear_down)
test.py
#import requests # this is commented
class TestClassA:
def test_1(self,set_up):
print "test A1 called"
print("username :-- %s and password is %s" % (set_up[0], set_up[1]))
def test_2(self):
print "test A2 called"
class TestClassB:
def test_1(self):
print "test B1 called"
pytest -s -v demo/test.py::TestClassA
此代码可以正常工作。 观察test.py
的第一行,它已被注释。 现在,如果我在取消注释import requests
运行相同的脚本,则会出现以下错误
ImportError while importing test module 'some_path/../demo/test.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/local/lib/python2.7/site-packages/six-1.11.0-py2.7.egg/six.py:709: in exec_
exec("""exec _code_ in _globs_, _locs_""")
demo/test.py:1: in <module>
import requests
E ImportError: No module named requests
在没有pytest的情况下执行可以正常工作(没有导入错误),而且,如果test.py
调用其他模块( which has import requests
)的功能,则会引发相同的错误。 request of pytest
的request of pytest
冲突吗? 我真的不明白,您能帮我吗?
哪个python: /Library/Frameworks/Python.framework/Versions/2.7/bin/python
pytest --version: 'imported from /usr/local/lib/python2.7/site-packages/pytest-3.8.2-py2.7.egg/pytest.pyc'
,这是失败的原因吗?
pytest-版本
This is pytest version 3.8.2, imported from /usr/local/lib/python2.7/site-packages/pytest-3.8.2-py2.7.egg/pytest.pyc
setuptools registered plugins:
celery-4.0.2 at /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/celery/contrib/pytest.py
hypothesis-3.8.2 at /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/hypothesis/extra/pytestplugin.pyc
pytest-cov-2.4.0 at /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pytest_cov/plugin.py
将以下代码行添加到脚本中并运行它:
from distutils.sysconfig import get_python_lib
print(get_python_lib())
现在检查输出,您将获得一些打印的路径,该路径指向python解释器当前正在使用的软件包的确切位置。
e.g. "/usr/lib/python2.7/dist-packages"
cd(更改目录)到上述路径, ls(列表目录)检查软件包是否存在; 如果没有 :
sudo pip3 install requests -t . # dot indicates current directory
否则,如果您有requirements.txt文件,则可以尝试:
sudo pip3 install -r requirements.txt -t "/usr/lib/python2.7/dist-packages"
#try this from the directory where "requirements.txt" file exists
现在运行您的脚本,请让我知道它是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.