ImportError:“ pytest”中没有名为请求的模块

时间:2018-10-09 03:57:02

标签: python macos 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的冲突吗?我真的不明白,您能帮我吗?

哪个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 --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

1 个答案:

答案 0 :(得分:0)

将以下代码行添加到脚本中并运行它:

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

现在运行您的脚本,请告诉我它是否有效