为什么 Order 在 MagicMock 断言的 Kwarg 参数中很重要?

Why does Order matter in Kwarg parameters in MagicMock asserts?

我有一个测试,我正在模拟对经理的过滤器调用。断言如下所示:

filter_mock.assert_called_once_with(type_id__in=[3, 4, 5, 6], finance=mock_finance, parent_transaction__date_posted=tran_date_posted)

被测试的代码如下所示:

agregates = Balance.objects.filter(
            finance=self.finance,type_id__in=self.balance_types,
            parent_transaction__date_posted__lte=self.transaction_date_posted
        )

我认为由于这些是 kwarg,所以顺序应该无关紧要,但测试失败了,即使每对的值都匹配。以下是我看到的错误:

AssertionError: Expected call: filter(type_id__in=[3, 4, 5, 6], parent_transaction__date_posted=datetime.datetime(2015, 5, 29, 16, 22, 59, 532772), finance=) Actual call: filter(type_id__in=[3, 4, 5, 6], finance=, parent_transaction__date_posted__lte=datetime.datetime(2015, 5, 29, 16, 22, 59, 532772))

这到底是怎么回事? kwarg 的顺序应该无关紧要,即使我的顺序与测试所断言的相匹配,测试仍然失败。

您的密钥不完全相同。在您的 assert_called_with 中,您有密钥 parent_transaction__date_posted,但在您的代码中,您使用的是密钥 parent_transaction__date_posted__lte。这就是导致您的测试失败的原因,而不是糟糕的排序。这是我自己的测试作为概念证明:

    >>> myobject.test(a=1, b=2)
    >>> mock_test.assert_called_with(b=2, a=1)
    OK
    >>> myobject.test(a=1, b__lte=2)
    >>> mock_test.assert_called_with(b=2, a=1)
    AssertionError: Expected call: test(a=1, b=2)
    Actual call: test(a=1, b__lte=2)

您需要更正您的测试或代码以使其匹配(包含 __lte 或不包含,具体取决于您的需要)