单元测试是否可以断言某个方法调用了 sys.exit()? [英] Is it possible for a unit test to assert that a method calls sys.exit()?

查看:42
本文介绍了单元测试是否可以断言某个方法调用了 sys.exit()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有时会调用的 Python 2.7 方法

I have a Python 2.7 method that sometimes calls

sys.exit(1)

是否可以进行单元测试以验证在满足正确条件时调用了这行代码?

Is it possible to make a unit test that verifies this line of code is called when the right conditions are met?

推荐答案

是的.sys.exit 引发 SystemExit,因此您可以使用 assertRaises:

Yes. sys.exit raises SystemExit, so you can check it with assertRaises:

with self.assertRaises(SystemExit):
    your_method()

SystemExit 的实例有一个属性 code 被设置为建议的退出状态,并且由 assertRaises 返回的上下文管理器有异常实例为exception,所以检查退出状态很容易:

Instances of SystemExit have an attribute code which is set to the proposed exit status, and the context manager returned by assertRaises has the caught exception instance as exception, so checking the exit status is easy:

with self.assertRaises(SystemExit) as cm:
    your_method()

self.assertEqual(cm.exception.code, 1)

 

sys.exit 文档:

退出 Python.这是通过引发 SystemExit 异常来实现的……可以在外层拦截退出尝试.

Exit from Python. This is implemented by raising the SystemExit exception ... it is possible to intercept the exit attempt at an outer level.

这篇关于单元测试是否可以断言某个方法调用了 sys.exit()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆