py.test找不到modu

2024-04-27 15:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

此问题与以下问题有关,但未在此处回答:

我有一个具有以下树结构的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,它就会工作。(但我不知道皮查姆身上发生了什么魔法……)

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


Tags: nopytesthomeworldlibpackagesusr
3条回答

我自己修好的。出于某种原因,pytest没有得到正确的virtualenv。在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

加上毒性,把这个加到你的毒性指数里:

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

您的错误信息显示:

ImportError: No module named 'mcts'

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

相关问题 更多 >