如何测试或模拟“if __name__ == '__main__'"内容 [英] How to test or mock "if __name__ == '__main__'" contents
问题描述
假设我有一个包含以下内容的模块:
Say I have a module with the following:
def main():
pass
if __name__ == "__main__":
main()
我想为下半部分编写一个单元测试(我想达到 100% 的覆盖率).我发现了执行 import/__name__
设置机制的 runpy 内置模块,但我不知道如何模拟或以其他方式检查 main() 函数被调用.
I want to write a unit test for the bottom half (I'd like to achieve 100% coverage). I discovered the runpy builtin module that performs the import/__name__
-setting mechanism, but I can't figure out how to mock or otherwise check that the main() function is called.
这是我迄今为止尝试过的:
This is what I've tried so far:
import runpy
import mock
@mock.patch('foobar.main')
def test_main(self, main):
runpy.run_module('foobar', run_name='__main__')
main.assert_called_once_with()
推荐答案
我会选择另一种替代方案,即从覆盖率报告中排除 if __name__ == '__main__'
,当然你可以仅当您的测试中已经有 main() 函数的测试用例时才这样做.
I will choose another alternative which is to exclude the if __name__ == '__main__'
from the coverage report , of course you can do that only if you already have a test case for your main() function in your tests.
至于为什么我选择排除而不是为整个脚本编写一个新的测试用例是因为如果正如我所说的那样你已经有一个 main()
函数的测试用例为脚本添加另一个测试用例(只是为了有 100% 的覆盖率)将只是一个重复的测试用例.
As for why I choose to exclude rather than writing a new test case for the whole script is because if as I stated you already have a test case for your main()
function the fact that you add an other test case for the script (just for having a 100 % coverage) will be just a duplicated one.
关于如何排除if __name__ == '__main__'
你可以写一个coverage配置文件并在section report中添加:
For how to exclude the if __name__ == '__main__'
you can write a coverage configuration file and add in the section report:
[report]
exclude_lines =
if __name__ == .__main__.:
可以在此处找到有关覆盖率配置文件的更多信息.
More info about the coverage configuration file can be found here.
希望能帮到你.
这篇关于如何测试或模拟“if __name__ == '__main__'"内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!