简体   繁体   English

如何使两个相等的unittest.mock.Mock对象具有相同的类型?

[英]How to make two equal unittest.mock.Mock objects to be of the same type?

I have to ensure that a Sequence is homogeneous, ie contains only objects of similar type. 我必须确保序列是同质的,即仅包含相似类型的对象。 So I added an assert like assert all(isinstance(obj, type(my_list[0])) for obj in my_list[1:]) That's not perfect but sufficient for my needs. 因此,我assert all(isinstance(obj, type(my_list[0])) for obj in my_list[1:])添加了一个assert断言,如assert all(isinstance(obj, type(my_list[0])) for obj in my_list[1:])虽然不够完美,但足以满足我的需求。 Unfortunately this causes problems when using it with unittest.mock.Mock : 不幸的是,这在与unittest.mock.Mock一起使用时会引起问题:

import unittest.mock as utm

class C:
    pass

my_list = [utm.Mock(spec_set=C), utm.Mock(spec_set=C)]

all(isinstance(obj, type(my_list[0])) for obj in my_list[1:])
>>>
False

In particular two mocks have different types, even if the have the same spec_set : 特别是两个模拟具有不同的类型,即使它们具有相同的spec_set

isinstance(utm.Mock(spec_set=C), type(utm.Mock(spec_set=C)))
>>>
False

Is there any way to configure the mocks so they are considered to be of the same type? 有什么方法可以配置模拟,因此它们被视为相同类型? Modifying the check would be an option too, as long as it does not get mock specific. 只要不是特定于模拟的,修改支票也是一种选择。

If that is of interest: I used Python 3.5. 如果感兴趣:我使用了Python 3.5。

why not do this? 为什么不这样做呢?

class A:
    pass

class MockA(Mock, A):
    pass

a1 = MockA()
a2 = MockA()

assert isinstance(a1, MockA) == isinstance(a2, MockA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM