[英]How to factorise python test cases with 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):
...
然后是具體的測試用例
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 Case中設置__test__ = False
,但在這種情況下,根本沒有執行任何測試(因為我認為這個字段是繼承的)。 我嘗試使用抽象基類(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'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.