对于一个简单的Python模块来说,非常常见的目录结构似乎是将单元测试分离到它们自己的测试目录中:
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
我的问题很简单,实际运行测试的通常方式是什么?我怀疑这对每个人来说都是显而易见的,除了我,但你不能只是从测试目录运行python test_antigravity.py,因为它的导入antigravity将失败,因为模块不在路径上。
我知道我可以修改PYTHONPATH和其他与搜索路径相关的技巧,但我不能相信这是最简单的方法——如果您是开发人员,这很好,但如果用户只是想检查测试是否通过,那么期望他们使用这种方法是不现实的。
另一种替代方法是将测试文件复制到另一个目录中,但这似乎有点愚蠢,并且没有注意到将它们放在一个单独的目录中。
那么,如果您刚刚下载源代码到我的新项目,您将如何运行单元测试?我更喜欢这样的答案:“要运行单元测试,请执行x。”
如果你使用VS Code,并且你的测试与你的项目位于同一级别,那么运行和调试你的代码就不能开箱即用。你能做的就是改变启动方式。json文件:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config:python.pythonPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
]
}
这里的关键行是envFile
"envFile": "${workspaceRoot}/.env",
在项目的根目录中添加.env文件
在.env文件中添加项目根目录的路径。这将临时添加
PYTHONPATH = C: \ \ PYTHON项目\ \ ROOT_DIRECTORY
路径到你的项目,你将能够使用调试单元测试从VS Code
实际运行测试的通常方式是什么
我使用的是Python 3.6.2
cd new_project
pytest test/test_antigravity.py
安装pytest: sudo pip install pytest
我没有设置任何路径变量,我的导入不会失败与相同的“测试”项目结构。
我注释掉了这些东西:如果__name__ == '__main__'像这样:
test_antigravity.py
import antigravity
class TestAntigravity(unittest.TestCase):
def test_something(self):
# ... test stuff here
# if __name__ == '__main__':
#
# if __package__ is None:
#
# import something
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
# from .. import antigravity
#
# else:
#
# from .. import antigravity
#
# unittest.main()
可以使用包装器来运行选定的或所有测试。
例如:
./run_tests antigravity/*.py
或者递归地运行所有测试使用globbing (tests/**/*.py)(通过shop -s globstar启用)。
包装器基本上可以使用argparse来解析参数,比如:
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*')
然后加载所有测试:
for filename in args.files:
exec(open(filename).read())
然后将它们添加到你的测试套件中(使用inspect):
alltests = unittest.TestSuite()
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj) and name.startswith("FooTest"):
alltests.addTest(unittest.makeSuite(obj))
并运行它们:
result = unittest.TextTestRunner(verbosity=2).run(alltests)
查看这个示例了解更多细节。
请参见:如何在一个目录中运行所有Python单元测试?
对于用户来说,最简单的解决方案是提供一个可执行脚本(runtests.py或类似的脚本),该脚本引导必要的测试环境,包括(如果需要的话)将根项目目录添加到sys. py。临时道路。这并不需要用户设置环境变量,类似这样的东西在引导脚本中工作得很好:
import sys, os
sys.path.insert(0, os.path.dirname(__file__))
然后你给用户的指令可以像“python runtests.py”一样简单。
当然,如果你需要的路径确实是os.path.dirname(__file__),那么你不需要将它添加到sys. path.dirname(__file__)。道路;Python总是将当前运行脚本的目录放在sys. exe的开头。路径,因此根据您的目录结构,将runtests.py定位到正确的位置可能就足够了。
此外,Python 2.7+中的unittest模块(在Python 2.6及更早的版本中被反向移植为unittest2)现在内置了测试发现,所以如果你想自动化测试发现,nose不再是必要的:你的用户指令可以像Python -m unittest discover一样简单。
同样的问题我已经有很长时间了。我最近选择的目录结构是这样的:
project_path
├── Makefile
├── src
│ ├── script_1.py
│ ├── script_2.py
│ └── script_3.py
└── tests
├── __init__.py
├── test_script_1.py
├── test_script_2.py
└── test_script_3.py
在test文件夹的__init__.py脚本中,我写了以下内容:
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH,"src"
)
sys.path.append(SOURCE_PATH)
对于共享项目来说,Makefile非常重要,因为它强制正确地运行脚本。下面是我放在Makefile中的命令:
run_tests:
python -m unittest discover .
The Makefile is important not just because of the command it runs but also because of where it runs it from. If you would cd in tests and do python -m unittest discover ., it wouldn't work because the init script in unit_tests calls os.getcwd(), which would then point to the incorrect absolute path (that would be appended to sys.path and you would be missing your source folder). The scripts would run since discover finds all the tests, but they wouldn't run properly. So the Makefile is there to avoid having to remember this issue.
我真的很喜欢这种方法,因为我不需要触及我的src文件夹,我的单元测试或我的环境变量,一切都运行顺利。