Skip to main content
 首页 » 编程设计

python之如何在 Python 中更改 TestCase 类的文档字符串

2025年05月04日11fff_TT

在 Python 2.5(实际上是 Jython)中,对于 UnitTest TestCase 类 - 没有 SetUpClass 方法,并且 __init__ 并不是真正可接受的(没有对 self 的引用)。 当我尝试更改 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__ 是可写的)。

UPDATED: but I want to avoid additional coding in the sub-class (i.e. inheriting super-class function to set docstring of sub-class), for example:

文件 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

请您参考如下方法:

已更新 - __file__ 是加载当前模块 的路径名,因此很自然地使用 __file__ DynamicTestCase.py 内部将导致路径 DynamicTestCase.py。但是,您可以像这样从子类中将路径传递到 setDocstring() 中:

DynamicTestCase.py:

class DynamicTestCase(unittest.TestCase): 
    def setDocstring(self, docstring=None): 
        if docstring is None: 
            docstring = __file__ 
        if os.path.exists(docstring): 
            name = os.path.split(docstring)[1] 
            docstring = os.path.splitext(name)[0] 
        setattr(self, '__doc__', docstring) 

MyTestCase.py:

class MyTestCase(DynamicTestCase): 
    def __init__(self, *args, **kwargs): 
        DynamicTestCase.__init__(self, *args, **kwargs) 
        self.setDocstring(__file__) 
 
    def test_print_docstring(self): 
        print 'MyTestCase Docstring = ', self.__doc__ 
 
    def test_new_docstring(self): 
        self.setDocstring('hello') 
        print 'MyTestCase Docstring = ', self.__doc__ 

输出:

MyTestCase Docstring =  MyTestCase 
MyTestCase Docstring =  hello 

其余答案

在您上面的原始代码中,__name__ 是一个字符串,而不是一个类。 Jython 正确地拒绝更改 str 类型的 __doc__ 属性。

您能解释一下为什么您想要更改 TestCase 的文档字符串吗?例如,您可以子类化 TestCase 并提供您自己的文档字符串:

class MyTestCase(unittest.TestCase): 
    "Docstring of MyTestCase" 

不确定您是否尝试过,但是 unittest2 package's TestCase 有 setUpClass, tearDownClass 类方法。它是 Python 2.7 改进的反向移植,可以与 Python 2.6 及更早版本一起使用。

Jython 允许您设置新式类的__doc__,但CPython 不允许。出于这个原因,如果您希望代码可移植,您可能想找到另一种方法来实现您的目标:

Jython 2.2.1 on java1.6.0_24 
>>> unittest.TestCase.__doc__ = 'foo bar' 
>>> unittest.TestCase.__doc__ 
'foo bar' 
 
Python 2.6.6 (r266:84292, Feb 12 2011, 01:07:21) 
>>> unittest.TestCase.__doc__ = 'foo bar' 
AttributeError: attribute '__doc__' of 'type' objects is not writable