Skip to main content
 首页 » 编程设计

python之python测试套件执行完毕后执行函数

2025年05月04日13zhoujg

我正在使用 python unittest 框架来做一些测试。

class AbstractTest(unittest.TestCase): 
  def setUp(self): 
 
 
  def tearDown(self): 
    # Close! 
    self.transport.close() 
 
  def testVoid(self): 
    self.client.testVoid() 
 
  def testString(self): 
    global test_basetypes_fails 
    try: 
      self.assertEqual(self.client.testString('Python' * 20), 'Python' * 20) 
    except AssertionError, e: 
      test_basetypes_fails = True 
      print test_basetypes_fails 
      raise AssertionError( e.args ) 
    try: 
      self.assertEqual(self.client.testString(''), '') 
    except AssertionError, e: 
      test_basetypes_fails = True 
      raise AssertionError( e.args ) 
 
  def testByte(self): 
    global test_basetypes_fails 
    try: 
      self.assertEqual(self.client.testByte(63), 63) 
    except AssertionError, e: 
      test_basetypes_fails = True 
      raise AssertionError( e.args ) 
    try: 
      self.assertEqual(self.client.testByte(-127), -127) 
    except AssertionError, e: 
      test_basetypes_fails = True 
      raise AssertionError( e.args ) 
 
  @classmethod 
  def tearDownClass(cls): 
    #sys.exit(1) 

当我执行测试时,我得到以下结果。

.................. 
---------------------------------------------------------------------- 
Ran 18 tests in 2.715s 
 
OK 

我需要在执行完后执行一段程序。我怎样才能做到这一点?当我将代码添加到类级别时,它会在完成以下部分输出后执行它。

.................. 

请您参考如下方法:

您需要编写自己的测试运行器,以便根据套件的结果返回退出代码。

您需要做的一切都在 unittest-module 文档中进行了解释。使用 TestLoader 加载您的套件,并使用 TextTestRunner 运行它。然后根据套件的结果,使用适当的退出代码调用 sys.exit。