How to test or mock “if __name__ == '__main__'” contents

前端 未结 7 673
無奈伤痛
無奈伤痛 2020-12-07 20:07

Say I have a module with the following:

def main():
    pass

if __name__ == \"__main__\":
    main()

I want to write a unit test for the b

7条回答
  •  -上瘾入骨i
    2020-12-07 20:30

    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.

    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.

    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.

    Hope this can help.

提交回复
热议问题