代码之家  ›  专栏  ›  技术社区  ›  James Lin

为什么python模拟assert_any_call不匹配

  •  0
  • James Lin  · 技术社区  · 1 年前

    给定assert_any_call的文档

    enter image description here

    我有一个日志声明要反驳

    ...
    logger.warning('Backup quantity is 0, supplied uuids %s, matched machines: %s', uuids, machines)
    ...
    

    请参阅我的单元测试的最后3行(前2行仅用于调查目的)

    # deliberate fail so it prints what it expects
    logger.warning.assert_not_called()
    
    # prints the params used in the official assert
    print('Backup quantity is 0, supplied uuids %s, matched machines: %s', [vm3_uuid], VirtualMachine.objects.none())
    
    # actual official assert
    logger.warning.assert_any_call('Backup quantity is 0, supplied uuids %s, matched machines: %s', [vm3_uuid], VirtualMachine.objects.none())
    

    测试的输出 assert_not_called 是:

    AssertionError: Expected 'warning' to not have been called. Called 2 times.
    Calls: [call('Backup quantity is 0, supplied uuids %s, matched machines: %s', ['232d7937-975c-457b-8a11-ac473d0e04a0'], <QuerySet []>),
     call('%s %s cannot find proxmox UUID from BIS', 'DEF-456', 'vm4')]
    

    参数打印为

    Backup quantity is 0, supplied uuids %s, matched machines: %s ['232d7937-975c-457b-8a11-ac473d0e04a0'] <QuerySet []>
    

    官方的断言失败了

    AssertionError: warning('Backup quantity is 0, supplied uuids %s, matched machines: %s', ['232d7937-975c-457b-8a11-ac473d0e04a0'], <QuerySet []>) call not found
    

    除非我错过了一些非常明显的东西,否则我不知道为什么 assert_any_call 会失败吗?

    2 回复  |  直到 1 年前
        1
  •  0
  •   user2357112    1 年前

    VirtualMachine.objects.none() 可能会返回一个空的QuerySet,但这并不意味着它将与另一个空QuerySet进行比较。您传递给的值 assert_any_call 不是传递给实际对象的对象 warning 调用,也不等于原始对象。

    为了使您的断言通过,查询集必须与进行相等比较 == .

        2
  •  0
  •   James Lin    1 年前

    我的答案只是补充@user2357112,我想我会分享我是如何克服我的问题的,但我不确定这是否是规范的方法。

    我创建了一个自定义 EmptyQuerySet 实现的类 __eq__ 检查所比较的对象是否是 QuerySet 类和 count() 返回0。

    class EmptyQuerySet(object):
        def __eq__(self, other):
            if isinstance(other, QuerySet) and other.count() == 0:
                return True
            return super(EmptyQuerySet, self).__eq__(other)
    

    然后我用它作为断言的一部分,如下所示,它奏效了。

    logger.warning.assert_any_call('Backup quantity is 0, supplied uuids %s, matched machines: %s', [vm3_uuid], EmptyQuerySet())