如何使用nosetests分解Python测试用例
我在图 f()、g() 和 h() 上有几个函数,它们针对同一问题实现不同的算法。我想使用单元测试框架对这些函数进行单元测试。
对于每种算法,几个约束应该始终有效(例如空图、只有一个节点的图等)。这些公共约束检查的代码不应重复。因此,我开始设计的测试架构如下:
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是在子类中指定。我尝试在 AbstractTest 案例中设置 __test__ = False
,但在这种情况下,根本不执行任何测试(因为我认为该字段是继承的)。我尝试使用抽象基类(abc.ABCMeta)但没有成功。我读过有关 MixIn 的内容,但没有任何结果(我对此不太有信心)。
我非常有信心我不是唯一一个尝试分解测试代码的人。你如何在 Python 中做到这一点?
谢谢。
I have several functions on graph f(), g() and h() that implements different algorithms for the same problem. I would like to unit-test these functions using unittest framework.
For each algorithm, several constraints should always be valid (such as empty graph, graph with only one node, and so on). The code for those common constraints checking should not be duplicated. So, the test architecture I started to design was the following:
class AbstractTest(TestCase):
def test_empty(self):
result = self.function(make_empty_graph())
assertTrue(result....) # etc..
def test_single_node(self):
...
Then the specific test cases
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'
... And so on for each algorithm
Unfortunately, nosetests, tries to execute each test in AbstractTest and it does not work since the actual self.function is specified in subclasses. I tried setting __test__ = False
in the AbstractTest Case, but in this case, no test is executed at all (since this field is inherited I suppose). I tried with abstract base class (abc.ABCMeta) without success. I have read about MixIn without any result (I am not really confident with it).
I am quite confident I am not the only one that try to factorize the test code. How do you do that in Python?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Nose 收集与正则表达式匹配的类 unittest.TestCase 的子类,因此最简单的解决方案是不执行这些操作:
Nose gathers classes that match a regex or are subclasses of unittest.TestCase, so the simplest solution is to do neither of those: