繁体   English   中英

AssertionError,尽管预期的调用看起来与实际调用相同

[英]AssertionError, altough the expected call looks same as actual call

我在django中发出了一个调用函数的命令。 该函数执行django orm调用:

def get_notes():
    notes = Note.objects.filter(number=2, new=1)
    return [x.note for x in notes]

我想修补实际的查找:

@mock.patch('Note.objects.filter', autospec=True)
def test_get_all_notes(self, notes_mock):
    get_notes()
    notes_mock.assert_called_once_with(number=2, new=1)

我得到以下断言错误:

AssertionError: Expected call: filter(number=2, new=1)
Actual call: filter(number=2, new=1)

我搜索谷歌和stackoverflow几个小时,但我仍然没有线索。 任何人都可以指出我正确的方向,我认为这可能是一个明显的错误,我正在做...

AFAIK你不能像这样使用patch() 补丁目标应该是package.module.ClassName形式的字符串。 我不太了解django,但我想Note是一个类,所以Note.objects.filter不是你可以导入的东西,因此在patch() 另外我认为patch()不能处理属性。 实际上我不太明白为什么修补程序可以工作。

尝试使用patch.object() ,它专门用于修补类属性。 这意味着Note已经在您的测试模块中导入。

@mock.patch.object(Note, 'objects')
def test_get_all_notes(self, objects_mock):
    get_notes()
    objects_mock.filter.assert_called_once_with(number=2, new=1)

我删除了autospec因为在这种情况下我不确定它是否能正常工作。 如果有效,你可以尝试把它放回去。

另一种选择可能是使用patch()来获取type(Note.objects) (可能是一些django类)。

正如我所说,我对django了解不多,所以我不确定这些是否有效。

暂无
暂无

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

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