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

发布于 2024-11-04 12:53:17 字数 1340 浏览 7 评论 0原文

在 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__ 是可写的)。

更新:但我想避免额外的编码 在子类中(即继承 设置文档字符串的超类函数 子类),例如:

File 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)

File MyTestCase.py 包括:

class MyTestCase(DynamicTestCase):
    def test_print_docstring(self):
        self.setDocstring()
        print 'MyTestCase Docstring = ', self.__doc__

但是,单元测试运行结果仍然是:

MyTestCase Docstring = DynamicTestCase

当我预期时 MyTestCase Docstring = MyTestCase

In Python 2.5 (Jython actually), for the UnitTest TestCase Class - there's is no SetUpClass method, and __init__ is not really acceptable (no refference to self).
When I try to change docstring inside the TestCase:

import os
fileName = os.path.split(__file__)[1]
testCaseName = os.path.splitext(fileName)[0]
setattr(__name__, '__doc__', testCaseName)

I'm getting:

setattr(__name__, '__doc__', testCaseName)
TypeError: readonly attribute

I tried to change the docstring by instantiate it into an object (where self.__doc__ is writable).

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:

File DynamicTestCase.py includes:

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)

File MyTestCase.py includes:

class MyTestCase(DynamicTestCase):
    def test_print_docstring(self):
        self.setDocstring()
        print 'MyTestCase Docstring = ', self.__doc__

But still, the unittest run result is:

MyTestCase Docstring = DynamicTestCase

When I expected MyTestCase Docstring = MyTestCase

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

⒈起吃苦の倖褔 2024-11-11 12:53:17

更新 - __file__ 是加载当前模块的路径名,因此自然会在 DynamicTestCase 中使用 __file__ 。 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__

Output:

MyTestCase Docstring =  MyTestCase
MyTestCase Docstring =  hello

其余答案

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

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

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

不确定您是否已经尝试过,但是 unittest2 包的 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

Updated - __file__ is the path name from which the current module was loaded, so naturally using __file__ inside DynamicTestCase.py will result in the path DynamicTestCase.py. However, you can just pass the path into setDocstring() from subclasses like this:

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__

Output:

MyTestCase Docstring =  MyTestCase
MyTestCase Docstring =  hello

Rest of answer

In your original code above __name__ is a string, not a class. Jython rightly rejects altering the __doc__ attribute on the str type.

Could you explain a bit about why you want to change TestCase's docstring? For example, you could subclass TestCase and give your own docstring:

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

Not sure if you've tried it yet, but the unittest2 package's TestCase has setUpClass, tearDownClass class methods. It's a backport of Python 2.7's improvements to work with Python 2.6 and prior.

Jython allows you to set the __doc__ of new-style classes, but CPython does not. For that reason you might want to find another way to accomplish your goal if you want your code to be portable:

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
故人爱我别走 2024-11-11 12:53:17

您正在获取 DynamicTestCase 文件的文件名,而不是调用该函数的文件。为了得到它,你必须进入它的堆栈框架:

  import inspect

  class DynamicTestCase(unittest.TestCase):
    def setDocstring(self, testCaseDocstring=None):
        if not testCaseDocstring:
            fileName = 'unknown.py'

            # Go up one stack frame and grab the file name
            stack = inspect.stack()
            try:
                frame = stack[1][0]
                fileName = frame.f_code.co_filename        
            finally:
                del stack

            testCaseDocstring = os.path.splitext(fileName)[0]

You are grabbing the filename of the DynamicTestCase file, not the file that is calling the function. In order to get that you have to go into it's stack frame:

  import inspect

  class DynamicTestCase(unittest.TestCase):
    def setDocstring(self, testCaseDocstring=None):
        if not testCaseDocstring:
            fileName = 'unknown.py'

            # Go up one stack frame and grab the file name
            stack = inspect.stack()
            try:
                frame = stack[1][0]
                fileName = frame.f_code.co_filename        
            finally:
                del stack

            testCaseDocstring = os.path.splitext(fileName)[0]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文