5

我在图 f()、g() 和 h() 上有几个函数,它们针对同一问题实现不同的算法。我想使用 unittest 框架对这些功能进行单元测试。

对于每种算法,几个约束应该始终有效(例如空图、只有一个节点的图等)。这些常见约束检查的代码不应重复。所以,我开始设计的测试架构如下:

class AbstractTest(TestCase):
  def test_empty(self):
      result = self.function(make_empty_graph())
      assertTrue(result....) # etc..
  def test_single_node(self):
      ...

然后是具体的测试用例

class TestF(AbstractTest):
  def setup(self):
      self.function = f
  def test_random(self):
      #specific test for algorithm 'f'

class TestG(AbstractTest):
  def setup(self):
      self.function = g
  def test_complete_graph(self):
      #specific test for algorithm 'g'

...等等每个算法

不幸的是,nosetests 尝试在 AbstractTest 中执行每个测试,但它不起作用,因为实际的 self.function 在子类中指定。我尝试__test__ = False在 AbstractTest Case 中设置,但在这种情况下,根本不执行任何测试(因为我想这个字段是继承的)。我尝试使用抽象基类(abc.ABCMeta)但没有成功。我读过关于 MixIn 的文章没有任何结果(我对它不是很自信)。

我很自信我不是唯一一个尝试分解测试代码的人。你如何在 Python 中做到这一点?

谢谢。

4

1 回答 1

2

Nose收集与正则表达式匹配的类或者是 unittest.TestCase 的子类,因此最简单的解决方案是不做这些:

class AlgoMixin(object):
  # Does not end in "Test"; not a subclass of unittest.TestCase.
  # You may prefer "AbstractBase" or something else.

  def test_empty(self):
    result = self.function(make_empty_graph())
    self.assertTrue(result)

class TestF(AlgoMixin, unittest.TestCase):
  function = staticmethod(f)
  # Doesn't need to be in setup, nor be an instance attribute.
  # But doesn't take either self or class parameter, so use staticmethod.

  def test_random(self):
    pass  # Specific test for algorithm 'f'.
于 2011-02-21T16:10:35.363 回答