如何测试或模拟“如果__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%的覆盖率).我发现了执行导入/__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配置文件并添加到部分报告中:
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.
希望这会有所帮助.
这篇关于如何测试或模拟“如果__name__ =='__main__'"内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!