py.test找不到模块

时间:2015-03-20 10:21:11

标签: python pytest

这个问题与以下问题有关,但在那里没有回答:

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

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

我在某个目录中创建了virtualenv

$ 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运行?

3 个答案:

答案 0 :(得分:15)

我自己修好了。由于某种原因,pytest没有得到virtualenv正确。在virtualenv中安装pytest解决了它

source virtualenvs/teste/bin/activate
pip install pytest

答案 1 :(得分:5)

我创建这个作为你的问题的答案和我自己的困惑。我希望它有所帮助。请注意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}

答案 2 :(得分:-2)

您的错误消息显示:

  

ImportError:没有名为&#39; mcts&#39;

的模块

查看您提供的目录结构,该错误告诉您,您没有“mcts&#39;模块/包。要修复它,你需要添加一个&#34; __ init __。py&#34;提交给&#39; mcts&#39;目录。之后,你应该可以运行&#39; py.test&#39;没有其他参数/​​设置。

相关问题