如何使用Python Unittest TearDownClass与TestResult.wasSuccessful()

时间:2014-09-02 19:11:34

标签: python python-unittest

我想致电setUpClasstearDownClass,以便每次测试只执行一次setupteardown。但是,当我打电话给tearDownClass时,它一直对我失败。我只想记录1个测试结果,如果两个测试都通过则为PASS,如果两个测试都失败则为FAIL。如果我只拨打setuptearDown,那么一切正常:

致电setUpClasstearDownClass

#!/usr/bin/python

import datetime
import itertools
import logging
import os
import sys
import time
import unittest

LOGFILE = 'logfile.txt'

class MyTest(unittest.TestCase):

    global testResult
    testResult = None

    @classmethod
    def setUpClass(self):

        ## test result for DB Entry:
        self.dbresult_dict = {
             'SCRIPT'       : 'MyTest.py',
             'RESULT'      : testResult,
        }

    def test1(self):

       expected_number = 10
       actual_number = 10

       self.assertEqual(expected_number, actual_number) 

   def test2(self):

       expected = True
       actual = True

       self.assertEqual(expected, actual)


   def run(self, result=None):
       self.testResult = result
       unittest.TestCase.run(self, result)

   @classmethod
   def tearDownClass(self):
       ok = self.testResult.wasSuccessful()
       errors = self.testResult.errors
       failures = self.testResult.failures
       if ok:
           self.dbresult_dict['RESULT'] = 'Pass'
       else:
           logging.info(' %d errors and %d failures',
                 len(errors), len(failures))
           self.dbresult_dict['RESULT'] = 'Fail'

if __name__ == '__main__':
   logger = logging.getLogger()
   logger.addHandler(logging.FileHandler(LOGFILE, mode='a'))
   stderr_file = open(LOGFILE, 'a')

   runner = unittest.TextTestRunner(verbosity=2, stream=stderr_file, descriptions=True)
   itersuite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
   runner.run(itersuite)
   sys.exit()
   unittest.main(module=itersuite, exit=True)

stderr_file.close()

错误:

test1 (__main__.MyTest) ... ok
test2 (__main__.MyTest) ... ok
ERROR
===================================================================
ERROR: tearDownClass (__main__.MyTest)
-------------------------------------------------------------------
Traceback (most recent call last):
   File "testTearDownClass.py", line 47, in tearDownClass
    ok = self.testResult.wasSuccessful()
AttributeError: type object 'MyTest' has no attribute 'testResult'
----------------------------------------------------------------------
Ran 2 tests in 0.006s
FAILED (errors=1)

1 个答案:

答案 0 :(得分:-4)

tearDownClass(self)更改为tearDownClass(cls),将setUpClass(self)更改为setUpClass(cls)