简体   繁体   English

Python:在单元测试中处理sys.exit吗?

[英]Python: handle sys.exit in unit tests?

I have a management command that can do stuff, or can return a sys.exit() . 我有一个可以执行操作或可以返回sys.exit()的管理命令。

I'm trying to handle the second case as follows in my unit tests: 我正在尝试在单元测试中处理第二种情况:

    with self.assertRaises(SystemExit) as cm:
        call_command('geocode_practices', *args, **opts)
    self.assertEqual(cm.exception, 1)

But this gives me: 但这给了我:

AssertionError: None != 1

What am I doing wrong? 我究竟做错了什么?

Also, what's the best way to handle the different scenarios? 另外,处理不同情况的最佳方法是什么? At the moment my test will fail if the script does not exit. 目前,如果脚本未退出,我的测试将失败。

Apparently the code inside your with block doesn't raise an exception. 显然, with块中的代码不会引发异常。 Note that sys.exit() just raises a SystemExit exception. 请注意, sys.exit()仅引发SystemExit异常。

And even if it did, the exception will not compare equal to 1. If not None , the cm.exception attribute contains the exception instance, not a number. 即使这样做,异常也不会等于1。如果不是None ,则cm.exception属性包含异常实例,而不是数字。

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

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