2017-05-31 51 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”版本。 –

相关问题