我被这个非常愚蠢的错误所困扰。我正在尝试使用 bluepy 在 Raspberry Pi 上运行 pytest。
pi@pi:~/bluepy/bluepy $ pytest test_asdf.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.9, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /home/pi/bluepy, inifile:
collected 0 items / 1 errors
==================================== ERRORS ====================================
______________ ERROR collecting bluepy/test_bluetoothutility.py _______________
ImportError while importing test module '/home/pi/bluepy/bluepy/test_asdf.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test_asdf:4: in <module>
from asdf import AsDf
asdf.py:2: in <module>
from bluepy.btle import *
E ImportError: No module named btle
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.65 seconds ============================
我意识到我的问题可能是 rootdir 显示的路径不正确。它应该是
/home/pi/bluepy/bluepy
我一直在阅读pytest docs但我只是不明白如何更改 rootdir。
最佳答案
你的问题与 Pytest 的 rootdir 无关。
Pytest 中的 rootdir 与 how test package names are constructed 没有任何联系并且 rootdir 没有添加到 sys.path
,正如您从遇到的问题中看到的那样。 (注意:被认为是 rootdir 的目录可能由于其他原因被添加到路径中,例如当您运行 python -m pytest
时它也是当前工作目录。)
正如其他人所描述的,这里的问题是顶级 bluepy/
不在 sys.path
.如果您只想让自己以交互方式运行某些东西,最简单的处理方法是按照 Cecil Curry's answer :cd
到顶级bluepy
并以 python -m pytest bluepy/test_asdf.py
运行 Pytest (或者只是 python -m pytest
,如果您希望它发现当前目录中或当前目录下的所有 test_*
文件并运行它们)。但我认为你需要使用 python -m pytest
,不仅仅是 pytest
, 以确保当前工作目录在路径中。
如果您希望建立一个其他人可以轻松运行而不会出现此类神秘故障的测试框架,您需要设置一个测试脚本来设置当前工作目录或 PYTHONPATH
或任何适当的。或使用 tox
.或者只是使用可以为您运行测试的标准工具使其成为 Python 包。 (所有这些都超出了这个问题的范围。)
顺便说一句,我同意Cecil对Mackie Messer's answer的意见。 ;乱搞 conftest.py
那样太困难和脆弱;几乎在任何情况下都有更好的解决方案。
附录:rootdir 的使用
据我所知,只有两件事可以使用 rootdir:
.pytest_cache/
除非另外指定(使用 cache_dir
配置选项),否则目录存储在 rootdir 中。 conftest.py
,它会always be loaded , 即使没有从 rootdir 中或根目录下加载测试文件。 documentation声称 rootdir 也用于生成 nodeid,但添加了
conftest.py
包含def pytest_runtest_logstart(nodeid, location):
print("logstart nodeid={} location={}".format(nodeid, location))
正在运行
pytest --rootdir=/somewhere/way/outside/the/tree
表明这是不正确的(尽管节点位置是相对于 rootdir 的)。
关于import - 更改 pytest 根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42996270/