2017-05-31 52 views
2

我寫了一個自定義斷言來測試兩個對象列表是否包含具有相同屬性的對象,現在我想使用否定測試來檢查兩個列表是否不相等。否定python中的自定義單元測試

from unittest import TestCase 
from classes import * 

class BaseTestCase(TestCase): 
    def assertCountObjectsEqual(self, list1, list2): 
     if len(list1) != len(list2): 
      raise AssertionError("lists must be the same length") 
     elif any(t1.__class__ != t2.__class__ or t1.__dict__ != t2.__dict__ for t1, t2 in zip(list1, list2)): 
      raise AssertionError("objects are not the same") 
     else: 
      pass 

肯定的情況下工作

class TestFillDemand(BaseTestCase): 
    def test_fruit(self): 
     self.assertCountObjectsEqual([Apple(), Apple(), Banana()], [Apple(), Apple(), Banana()]) 

但我希望能夠重用的代碼,類似如下:

def test_fruit_unequal(self): 
     self.assertRaises(AssertionError, self.assertCountObjectsEqual([Apple(), Apple(), Banana()], [Apple(), Banana()])) 

,而不必重新定義assertCountObjectsUnequal方法。不幸的是,上面的代碼不起作用。

有沒有簡單的方法來做到這一點?

回答

2

一種選擇是將對象列表包裝到定義__eq__() magic method的自定義「集合」類中。這樣一來,你就可以利用內置的斷言方法 - assertEqual()assertNotEqual()

from unittest import TestCase 

class Apple: 
    pass 


class Banana: 
    pass 


class Collection: 
    def __init__(self, objects): 
     self.objects = objects 

    def __eq__(self, other): 
     if len(self.objects) != len(other.objects): 
      return False 
     if any(t1.__class__ != t2.__class__ or t1.__dict__ != t2.__dict__ for t1, t2 in zip(self.objects, other.objects)): 
      return False 

     return True 


class BaseTestCase(TestCase): 
    def test_fruit_equal(self): 
     self.assertEqual(Collection([Apple(), Apple(), Banana()]), Collection([Apple(), Apple(), Banana()])) 

    def test_fruit_unequal(self): 
     self.assertNotEqual(Collection([Apple(), Apple(), Banana()]), Collection([Apple(), Banana()])) 

兩個測試通過。

+0

這是有效的,但我想知道是否有辦法否定測試,而不必單獨定義「Not」版本。 –

相關問題