问题描述
我已经在Django中编写了一个测试,并且我正在。这是测试:
I have written a test in Django, and I'm using unittest.mock.ANY
to ignore certain values in a dictionary. Here is the test:
from django.test import TestCase
from django.contrib.auth import get_user_model
import unittest.mock as mock
class Example(TestCase):
def test_example(self):
user = get_user_model().objects.create_user(username='example')
result = {'user': user, 'number': 42}
self.assertEqual(
result,
{'user': mock.ANY, 'number': 42}
)
如果我运行此测试,我希望它能通过。相反,我遇到了这种失败:
If I run this test, I expect it to pass. Instead, I get this failure:
======================================================================
FAIL: test_example (example.tests.Example)
----------------------------------------------------------------------
Traceback (most recent call last):
File "example/tests.py", line 18, in test_example
'number': 42,
AssertionError: {'user': <User: example>, 'number': 42} != {'user': <ANY>, 'number': 42}
- {'number': 42, 'user': <User: example>}
? ^^^^^^^^^^^^^
+ {'number': 42, 'user': <ANY>}
? ^^^
为什么不在这种情况下有效?
Why doesn't ANY
work in this case? It seems to work with strings and numbers.
推荐答案
assertEqual
,在在比较两个参数的过程中,计算表达式 user ==模拟.ANY
。以标准方式, left 参数确定哪个函数实际实现 ==
。在这种情况下,您有 user .__ eq __(mock.ANY)
。看来无论 user
是什么类型,其 __ eq __
方法仅返回 False
表示意外类型。如果它引发了 NotImplemented
,则该语言将落在 mock.ANY .__ eq __(user)
上,这可能会返回 True
。
assertEqual
, in the course of comparing its two arguments, evaluates the expression user == mock.ANY
. In standard fashion, the left argument determines which function actually implements ==
. In this case, you have user.__eq__(mock.ANY)
. It appears that whatever type user
is, its __eq__
method simply returns False
for an unexpected type. If it raised NotImplemented
instead, the language would fall back on mock.ANY.__eq__(user)
, which could return True
.
如果将通话更改为
self.assertEqual(
{'user': mock.ANY, 'number': 42},
result,
)
然后得到的比较结果 mock.ANY ==用户
将返回 True
如预期。
then the resulting comparison mock.ANY == user
will return True
as expected.
这篇关于为什么unittest.mock.ANY无法与Django对象一起正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!