Skip to main content
 首页 » 编程设计

python之在 python 中否定自定义单元测试

2024年10月01日7kenshinobiy

我已经编写了一个自定义断言来测试两个对象列表是否包含具有相同属性的对象,现在我想使用测试的否定来检查两个列表是否不相等。

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 方法。不幸的是,上面的代码不起作用。

有没有简单的方法可以做到这一点?

请您参考如下方法:

一个选择是将您的对象列表包装到定义 __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()])) 

两个测试都通过了。