Skip to main content
 首页 » 编程设计

python之如何将测试名称和模块添加到结果中的测试文档字符串

2025年04月02日37pengyingh

我正在使用 django_nose 的 NoseTestSuiteRunner 来运行测试。目前,如果测试有文档字符串,它将打印在测试的控制台上 (TestCase.ShortDescrption()),如果它是 None,则测试的名称 (TestCase. id()) 被打印,我想将 TestCase.id() 添加到 TestCase.ShortDescription() 以便打印 TestCase.id() 无论如何文档字符串的存在。

样本测试:

class Foo(unittest.TestCase): 
      def test_bar_1(self): 
          """ this is docstring 1""" 
          pass 
 
      def test_bar_2(self): 
          """ this is docstring 2""" 
          self.fail() 

所以对于结果而不是

this is a docstring 1 ... ok 
this is a docstring 2 ... Fail 

我要

test_bar_1(path.to.test.Foo) this is a docstring 1 ... ok 
test_bar_2(path.to.test.Foo) this is a docstring 2 ... Fail 

请您参考如下方法:

我修改了 TestCase.shortDescription() 的实现返回两个 TestCase.__str__和 TestCase._testMethodDoc如下:

class Foo(unittest.TestCase): 
 
      def shortDescription(self): 
          doc = self.__str__() +": "+self._testMethodDoc 
          return doc or None  
 
      def test_bar_1(self): 
          """ this is docstring 1""" 
          pass 
 
      def test_bar_2(self): 
          """ this is docstring 2""" 
          self.fail() 

所以 nosetests -v <module-name>.py 的结果是:

test_bar_1(path.to.test.Foo): this is a docstring 1 ... ok 
test_bar_2(path.to.test.Foo): this is a docstring 2 ... Fail 

注意:我会尽快为它添加一个 Nose 插件。