gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:11:59 24 4
gpt4 key购买 nike

我要考下一个类:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com