pie*_*rre 5 python oop refactoring unit-testing nosetests
我在图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):
...
Run Code Online (Sandbox Code Playgroud)
然后是具体的测试用例
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'
Run Code Online (Sandbox Code Playgroud)
......对于每种算法都是如此
不幸的是,nosetests尝试在AbstractTest中执行每个测试并且它不起作用,因为实际的self.function是在子类中指定的.我尝试__test__ = False在AbstractTest Case中进行设置,但在这种情况下,根本没有执行任何测试(因为我认为这个字段是继承的).我尝试使用抽象基类(abc.ABCMeta)但没有成功.我已经阅读了关于MixIn而没有任何结果(我对此并不十分自信).
我非常有信心我不是唯一一个试图将测试代码分解的人.你是如何用Python做到的?
谢谢.
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'.
Run Code Online (Sandbox Code Playgroud)