py.test 找不到模块



这个问题与以下问题有关,但没有得到回答:

  • pytest';的PATH问题;ImportError:没有名为YadaYadaYada的模块'
  • Py.test没有命名的模块*

我有一个具有以下树结构的python模块:

mcts
|- setup.py
|- mcts
 |- __init__.py
 |- uct.py
 |- toy_world_state.py
 |- test
  |- test_uct.py
  |- test_toy_world_state.py

我在某个目录中创建了一个虚拟机

$ mkdir virtual
$ virtualenv --system-site-packages virtual
$ source virtual/bin/activate

然后我安装我的包:

$ cd /path/to/mcts
$ pip install -e .

现在我试着运行测试:

$ py.test mcts
================================================== test session starts ==================================================
platform linux -- Python 3.4.2 -- py-1.4.26 -- pytest-2.6.4
collected 0 items / 2 errors 
======================================================== ERRORS =========================================================
__________________________________ ERROR collecting mcts/test/test_toy_world_state.py ___________________________________
mcts/test/test_toy_world_state.py:4: in <module>
    from mcts.toy_world_state import *
E   ImportError: No module named 'mcts'
________________________________________ ERROR collecting mcts/test/test_uct.py _________________________________________
mcts/test/test_uct.py:4: in <module>
    from mcts.uct import *
E   ImportError: No module named 'mcts'
================================================ 2 error in 0.02 seconds ===============================================

如果我走到任何路径并尝试在ipython中导入模块,它会起作用:

$ cd
$ ipython
In [1]: import mcts.uct
In [2]: mcts.uct? 
Type:        module
String form: <module 'mcts.uct' from '/home/johannes/src/mcts/mcts/uct.py'>
File:        /home/johannes/src/mcts/mcts/uct.py
Docstring:   <no docstring>

如果我在pycharm中运行pytest,它会起作用。(但我不知道pycharm里会发生什么魔法…)

echo $PYTHONPATH返回一个空字符串时,sys.path似乎是正确的:

>>> import sys; print(sys.path)
['/home/johannes/src/mcts/virtualenvs/teste/lib/python3.4/site-packages', 
'/home/johannes/src/mcts', '', '/usr/bin', 
'/usr/lib/python3.4/site-packages/GitPython-0.3.2.RC1-py3.4.egg', 
'/usr/lib/python34.zip', '/usr/lib/python3.4', 
'/usr/lib/python3.4/plat-linux', '/usr/lib/python3.4/lib-dynload', 
'/usr/lib/python3.4/site-packages', 
'/usr/lib/python3.4/site-packages/IPython/extensions', 
'/home/johannes/.ipython']

我该怎么办,才能运行pytests?

我自己修复了它。由于某种原因,pytest没有得到正确的virtualenv。在虚拟机中安装pytest解决了问题

source virtualenvs/teste/bin/activate
pip install pytest

我创建这个是为了回答您的问题和我自己的困惑。我希望它能有所帮助。注意py.test命令行和tox.ini中的PYTHONPATH。

https://github.com/jeffmacdonald/pytest_test

具体来说:你必须告诉py.test和tox在哪里可以找到你包含的模块。

使用py.test可以做到这一点:

PYTHONPATH=. py.test

使用tox,将此添加到您的tox.ini中:

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

您的错误消息显示:

ImportError:没有名为"mcts"的模块

查看您提供的目录结构,该错误会告诉您没有"mcts"模块/包。要修复此问题,您需要在'mcts'目录中添加一个"__init__.py"文件。之后,您应该能够在没有其他参数/设置的情况下运行"py.test"。

最新更新