修改testtools框架,将测试结果显示用例注释名字

本文介绍如何修改TestTools框架以显示测试用例的注释而非仅显示函数名称。通过修改`shortDescription`方法并增加一行代码来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在之前介绍的测试框架testtool中,发现测试结果中显示的都是测试用例的函数名,并没有将注释显示出来

这很不符合国人使用阿,没办法,自己动手来改改吧

首先,testtools是继承unittest的一个工具,所以应该存在unittest TestCase的相关函数

 

看看testtools.testcase原码吧,发现,不显示注释的奥秘在这里

class TestCase(unittest.TestCase):
    """Extensions to the basic TestCase.

    :ivar exception_handlers: Exceptions to catch from setUp, runTest and
        tearDown. This list is able to be modified at any time and consists of
        (exception_class, handler(case, result, exception_value)) pairs.
    :ivar force_failure: Force testtools.RunTest to fail the test after the
        test has completed.
    :cvar run_tests_with: A factory to make the ``RunTest`` to run tests with.
        Defaults to ``RunTest``.  The factory is expected to take a test case
        and an optional list of exception handlers.
    """

......
......

def shortDescription(self):
        return self.id()
       

原来这里没显示注释,那来改改吧,直接上代码

def __init__(self, *args, **kwargs):
        """Construct a TestCase.

        :param testMethod: The name of the method to run.
        :keyword runTest: Optional class to use to execute the test. If not
            supplied ``RunTest`` is used. The instance to be used is created
            when run() is invoked, so will be fresh each time. Overrides
            ``TestCase.run_tests_with`` if given.
        """
        runTest = kwargs.pop('runTest', None)
        super(TestCase, self).__init__(*args, **kwargs)
        self._reset()
        test_method = self._get_test_method()
        if runTest is None:
            runTest = getattr(
                test_method, '_run_test_with', self.run_tests_with)
        self.__RunTest = runTest
        self._testMethodDoc = test_method.__doc__

这里,加入最后一行

self._testMethodDoc = test_method.__doc__


def shortDescription(self):
        #return self.id()
        doc = self._testMethodDoc
        return doc and doc.split("\n")[0].strip() or None

这里再改成这样。

再次运行,结果如下:

======================================================================
FAIL: i dont konw
----------------------------------------------------------------------
_StringException: Traceback (most recent call last):
  File "test_case\testtools_learn.py", line 34, in te
st_case_2
    assert 2 == 3
AssertionError


----------------------------------------------------------------------

很好,显示为用例的注释名了。



转载于:https://www.cnblogs.com/landhu/p/9068694.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值