【发布时间】:2018-10-09 17:05:46
【问题描述】:
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 的冲突吗?这个我真的不明白,你能帮帮我吗?
which python:/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonpytest --version:'imported from /usr/local/lib/python2.7/site-packages/pytest-3.8.2-py2.7.egg/pytest.pyc',这是失败的原因吗?
pytest --version
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
【问题讨论】:
-
requests 没有为您使用的解释器/venv 安装。
-
@KlausD。这对这里有什么影响?因为,即使从 python 交互,我也可以成功导入请求。
-
不同的Python解释器(版本)还是venv?
-
不,它是同一个 /Library/Frameworks/Python.framework/Versions/2.7/bin/python
-
那么当你运行
/Library/Frameworks/Python.framework/Versions/2.7/bin/python -c "import requests"时,你会得到任何输出吗?