首页 文章

py.test找不到模块

提问于
浏览
14

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

我有一个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 回答

  • -3

    您的错误消息说:

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

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

  • 4

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

    source virtualenvs/teste/bin/activate
    pip install pytest
    
  • 15

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

相关问题