简体   繁体   English

模拟如果 __name__ == "__main__":

[英]Mock if __name__ == "__main__":

I need to write test cases for my project, however I am stuck at one line of code.我需要为我的项目编写测试用例,但是我被困在一行代码中。 How can I mock this line if __name__ == "__main__" ? if __name__ == "__main__"我该如何模拟这一行? Please provide ways to do this.请提供执行此操作的方法。 Any help/advice will be helpful.任何帮助/建议都会有所帮助。

Don't.别。 You don't need to.你不需要。

Instead of writing而不是写作

if __name__ == '__main__':
    # complicated stuff to test...

write

def main():
    # complicated stuff to test...

if __name__ == '__main__':
    main()

Then you can just test main like any other function, without having to mess with __name__ or try to somehow get the if __name__ == '__main__' block to run twice when you want to run two tests on it.然后,您可以像测试任何其他函数一样测试main ,而不必弄乱__name__或尝试以某种方式让if __name__ == '__main__'块在您想对其运行两次测试时运行两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM