在 Python 2.5(实际上是 Jython)中,对于 UnitTest TestCase 类 - 没有 SetUpClass 方法,并且__init__
不是真正可以接受的(没有参考自我)。当我尝试更改 TestCase 中的文档字符串时:
import os
fileName = os.path.split(__file__)[1]
testCaseName = os.path.splitext(fileName)[0]
setattr(__name__, '__doc__', testCaseName)
我越来越:
setattr(__name__, '__doc__', testCaseName)
TypeError: readonly attribute
我试图通过将文档字符串实例化为一个对象(在哪里self.__doc__
是可写的)来更改文档字符串。
更新:但我想避免在子类中进行额外的编码(即继承超类函数来设置子类的文档字符串),例如:
文件 DynamicTestCase.py 包括:
class DynamicTestCase(unittest.TestCase):
def setDocstring(self, testCaseDocstring=None):
if not testCaseDocstring:
fileName = os.path.split(__file__)[1]
testCaseDocstring = os.path.splitext(fileName)[0]
setattr(self, '__doc__', testCaseDocstring)
文件 MyTestCase.py 包括:
class MyTestCase(DynamicTestCase):
def test_print_docstring(self):
self.setDocstring()
print 'MyTestCase Docstring = ', self.__doc__
但是,unittest 的运行结果仍然是:
MyTestCase Docstring = DynamicTestCase
当我期望MyTestCase Docstring = MyTestCase