【发布时间】:2021-01-06 08:41:55
【问题描述】:
我是 pytest 和测试的新手。我有一个像下面这样的简单程序说hi.py
def foo():
print('hello world')
def bar():
print('hello python')
if __name__ == "__main__":
foo()
bar()
我可以像这样运行上面的程序
python3 hi.py
我在test_hi.py 中有几个测试用例,如下所示
import pytest
def test_foo()
pass
def test_bar()
pass
为了增加代码覆盖率,我还想以python3 hi.py 即如果__name__==__main__: 方式对其进行测试。我不知道如何使用来自test_hi.py 的测试用例来做到这一点。请帮忙。谢谢。
我正在使用 pytest 测试模块
python -m pytest --cov=hi.py
【问题讨论】:
-
if __name__ == "__main__":块中的行无法通过导入访问,这就是重点。要运行它们,您必须实际运行整个程序,而不仅仅是测试。如果其中有你想要测试的逻辑,然后将其提取到一个你可以导入和练习的函数中,但在这种情况下它是微不足道的。 -
对于使用 Click for CLI 的应用程序,您可以查看一些插件,例如 pypi.org/project/pytest-console-scripts 或 pypi.org/project/pytest-click。如果我理解你的问题是正确的。
-
我意识到我的问题是stackoverflow.com/questions/5850268/… 的重复,虽然我不确定该选择哪一个或者我应该免于覆盖范围
-
您可以编写一个集成测试来执行例如
runpy.run_path("hi.py", run_name="__main__")并验证脚本的行为。然而,对于简单的主要块,使用pragma: no cover忽略覆盖更容易。如果您有复杂的主块,则应将它们重构为单个函数def main(): ...并通过调用main()单独测试。
标签: python python-3.x unit-testing pytest code-coverage