2

我想测试下一节课:

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 很陌生,我第一次尝试测试一些东西。

4

2 回答 2

1

I would recommend using the assertRaises context manager. Here is an example test that ensures that the play() method exits:

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)
于 2013-08-22T19:20:49.347 回答
0

正如您在回溯中看到的那样, *在您调用它时sys.exit()会引发异常。SystemExit所以,这就是你想用鼻子测试的assert_raises()。如果您正在使用unittest2.TestCasethat编写测试self.assertRaises

*实际上您使用的是普通内置的,exit()但您确实应该sys.exit()在程序中使用。

于 2013-08-11T23:07:19.587 回答