如何使用assert_raises来捕获SystemExit异常

时间:2013-08-12 08:48:33

标签: python testing assert nose

我有我要测试的代码:

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)]
                sys.exit(1)

如何使用accept_raises检查是否退出?

def test_End():
    end=End().play()
    assert_raises(what should I put here)

2 个答案:

答案 0 :(得分:1)

我更喜欢@raises装饰器

from nose.tools import raises

@raises(SystemExit)
def test_End():
    end=End().play()

答案 1 :(得分:0)

您可以在assertRaises中抓住SystemExit例外:

with self.assertRaises(SystemExit):
    End().play()

或通过mock修补sys.exit

with patch.object(sys, 'exit') as mock_method:
    End().play()
    self.assertTrue(mock_method.called)