Python unittest:如何重用TestCase.assert函数

时间:2011-05-08 07:28:32

标签: python

我正在编写unittest.TestCase的子类来抽象我们代码的一些细节,我想使用自己的断言函数,但是我需要将这个断言结果报告给测试结果。我试图重用像这样的unittest断言函数:

class MyTestCase(unittest.TestCase):
    def assertState(state, value):
        if state_dict[state] == value:
            self.assertTrue(True)
        else:
            self.assertTrue(False)

问题是我的MyTestCase实例中的asserrState调用将报告assertError,而不是报告测试结果对象的错误。

请建议我如何在unittest.TestCase的子类中编写自己的断言函数。

编辑: 我想要实现的是提供我们自己的MyTestCase类作为基类,其中包含更多带有业务逻辑的断言函数。这样,真正的测试可以只是MyTestCase的子类并使用这些断言而不重复相同的代码。这意味着我希望能够在MyTestCase的子类中调用MyTestCase.assertState,并仍然将测试失败报告给该具体测试结果。如下所示。

class ConcreteTestCase(MyTestCase):
    def test_1(self):
        #do something here
        self.assertState("state", "on")

如果有办法,请告诉我。

3 个答案:

答案 0 :(得分:2)

class MyTestCase(unittest.TestCase):
  def assertState(self, state, value):
    self.assertEqual(value, self.state_dict[state])

  def test_whatever(self):
    self.assertState(1, 1)
    self.assertState(2, 2)

答案 1 :(得分:1)

首先,您忘记了self参数。其次,你是如何运行它的?如果您真的想要测试结果对象,那就是这样做的:

In [1]: import unittest

In [2]: state_dict = {1:2}

In [3]: class MyTestCase(unittest.TestCase):
   ...:         def assertState(self, state, value):
   ...:             if state_dict[state] == value:
   ...:                 self.assertTrue(True)
   ...:         else:
   ...:                 self.assertTrue(False)
   ...:     def runTest(self):
   ...:         self.assertState(1,2)
   ...:         self.assertState(1,1)
   ...: 

In [4]: r = unittest.TestResult()

In [5]: MyTestCase().run(r)

In [6]: r
Out[6]: <unittest.TestResult run=1 errors=0 failures=1>

In [7]: r.errors
Out[7]: []

In [8]: r.failures
Out[8]: 
[(<__main__.MyTestCase testMethod=runTest>,
  'Traceback (most recent call last):\n  File "<ipython console>", line 9, in runTest\n  File "<ipython console>", line 6, in assertState\nAssertionError\n')]

答案 2 :(得分:1)

非常迟到的回复,但最后是一个解决方案,因为我在定义自己的TestCase子类时遇到了同样的问题。对于寻找同样事物的其他人来说可能会有所帮助。

您只需要在定义类的模块中添加__unittest = True

import unittest

__unittest = True

class MyTestCase(unittest.TestCase):
    def assertState(state, value):
        if state_dict[state] != value:
            standardMsg = 'the state %s does not match %s' % (state, value)
            self.fail(self._formatMessage(msg, standardMsg))

现在,用户定义的断言方法的行为与unittest.TestCase方法完全相同,并且在失败时不会显示不需要的堆栈跟踪。

适用于Python 2.7

来源:http://www.gossamer-threads.com/lists/python/python/1014779