我想调用
setUpClass
和 tearDownClass
,以便每次测试只执行一次 setup
和 teardown
。然而,当我打电话给tearDownClass
时,它总是失败。我只想记录 1 个测试结果,如果两个测试都通过则为 PASS,如果两个测试都失败则为 FAIL。如果我只调用 setup
和 tearDown
那么一切正常:
呼叫
setUpClass
和tearDownClass
:
#!/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)
就像 @Marcin 已经指出的那样,您正在以不符合预期的方式使用单元测试框架。
assertEqual(given, expected)
。然后,Unittest 将收集失败的摘要。您不必手动执行此操作。setUp()
将在每个测试方法之前调用
tearDown()
将在每个测试方法之后被调用
setUpClass()
每类一次(在本类的第一个测试方法之前)
tearDownClass()
每堂课一次(在本堂课的最后一个测试方法之后)
tearDownClass(self)
更改为
tearDownClass(cls)
,将 setUpClass(self)
更改为 setUpClass(cls)
。