testing - 如何测试程序是否退出

标签 testing python-2.7 exit nosetests

我要考下一个类:

from random import randint

class End(object):
          def __init__(self):
             self.quips=['You dead', 'You broke everything you can','You turn you head off']

          def play(self):
                print self.quips[randint(0, len(self.quips)-1)]
                exit(1)

我想用 nosetests 测试它,这样我就可以看到该类使用代码 1 正确退出。我尝试了不同的变体,但 nosetest 返回类似的错误

  File "C:\Python27\lib\site.py", line 372, in __call__
    raise SystemExit(code)
SystemExit: 1

----------------------------------------------------------------------
Ran 1 test in 5.297s

FAILED (errors=1)

当然我可以假设它退出但我希望测试返回 OK 状态而不是错误。对不起,如果我的问题可能很愚蠢。我是 python 的新手,我第一次尝试测试一些东西。

最佳答案

我建议使用 assertRaises context manager .这是确保 play() 方法退出的示例测试:

import unittest
import end

class TestEnd(unittest.TestCase):
    def testPlayExits(self):
        """Test that the play method exits."""
        ender = end.End()
        with self.assertRaises(SystemExit) as exitexception:
            ender.play()
        # Check for the requested exit code.
        self.assertEqual(exitexception.code, 1)

关于testing - 如何测试程序是否退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176658/

相关文章:

testing - 什么是 CMS 测试?

testing - 如何使用 Spock 使用 Stub(class, closure) 制作 Stub

python - 生成 n 倍的拆分索引

c++ - 为什么 gdb "u"命令不退出循环?

bash - 基于 bash 中循环操作的带有错误代码的退出脚本

ruby - 使用 Ruby 测试命令行应用程序界面的最佳方法是什么?

unit-testing - 从 MockRepository 检索数据?

android - sl4a python 为安卓手机做一个Toast

python - 为什么类中需要 Thread.__init__() ?

c - 如何避免 C 容器服务器的用户定义库程序中出现 "exit"?