Python导入使用鼻子进行测试-在当前软件包之上导入模块的最佳实践是
这是一个经常以不同形式提出的问题,通常会得到大声笑,您做得不好"的回答.可以肯定的是,这是因为有人(包括我在内)正在尝试将其用作实现方式,并且解决方案并不明显(如果您之前未曾尝试过的话).
This is a question which is asked frequently in different forms, and often obtains "lol you're not doing it properly" responses. Pretty sure that's because there's a common sense scenario people (including me) are trying to use as an implementation, and the solution is not obvious (if you've not done it before).
会接受让蝇从瓶子中飞出来"的答案.
Would accept an answer which "lets the fly out of the bottle".
给予
project/
__init__.py
/code
__init__.py
sut.py
/tests
__init__.py
test_sut.py
tests_sut.py的开始位置:
Where tests_sut.py starts:
import code.sut
在根目录中运行鼻子测试会导致:
Running nosetests in the root dir leads to:
ImportError: No module named code.sut
经过的地点:
a)使用
from ..code import sut
b)将项目的根目录添加到PYTHONPATH
b) add root of project to PYTHONPATH
c)使用
sys.path.append
在每个测试模块开始处的导入之前添加..路径.
to add the .. path before the imports at the start of each test module.
d)只记得做一个
setup.py
在项目上将模块安装到站点程序包中,然后再运行测试.
on the project to install the modules into the site-packages before running tests.
因此,要求将测试放置在测试包根目录下,并且可以访问该项目.以上每种对我来说都不是自然"的,事实证明是有问题的,或者看起来太辛苦了!
So the requirement is to have tests located beneath the test package root which have access to the project. Each of the above don't feel "natural" to me, have proved problematic or seem like too much hard work!
在Java中这是可行的,但是基本上是通过构建工具/IDE将所有类放在类路径上.也许问题出在我期望Python产生魔力"?在Flask网络框架测试中已经注意到,选项d)似乎是首选.
In java this works, but basically by dint of your build tool / IDE placing all your classes on the classpath. Perhaps the issue is I'm expecting "magic" from Python? Have noted in the Flask webframework tests, option d) seems to be preferred.
在任何情况下,以下建议采用首选解决方案的陈述都会消除我自己的不自然"感觉.
In any case, statements below recommending a preferred solution would remove the feeling of "unnaturalness" in my own.
您已经很好地回答了您的问题. 首选D(安装到系统位置)作为可分发代码.我通常使用C(修改sys.path),因为我不希望在系统范围内安装数百个自定义库.从理论上讲,A(相对导入)似乎更好,但是在某些情况下它会失败. B(PYTHONPATH)是正确的,我认为这仅是出于测试目的.
You have answered your question pretty well already.. D (install to system location) is preferred for distributable code. I usually use C (modify sys.path) because I don't want system-wide installs of my hundreds of custom libs. In theory A (relative import) seems nicer, but there are cases where it fails. B (PYTHONPATH) is right out, really only for testing purposes in my opinion.
这几乎总结了所有选项.您偏爱的选项(Python神奇地知道在哪里寻找)实际上不是可行的解决方案,因为它可能导致无法预测的结果,例如从不相关的项目中自动查找库.
That pretty much sums up all of the options. The option you prefer (Python magically knows where to look) is really not a workable solution because it can lead to unpredictable results, such as automagically finding libraries from unrelated projects.
我认为最好的方法是将其放在程序的入口点:
In my opinion, the best thing to do is put this at the entry point(s) to your program:
import sys, os
sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path