Arj*_*tra 5 python django mocking
我在 django 中做了一个调用函数的命令。该函数执行 django orm 调用:
def get_notes():
notes = Note.objects.filter(number=2, new=1)
return [x.note for x in notes]
Run Code Online (Sandbox Code Playgroud)
我想修补实际查找:
@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)
Run Code Online (Sandbox Code Playgroud)
我收到以下断言错误:
AssertionError: Expected call: filter(number=2, new=1)
Actual call: filter(number=2, new=1)
Run Code Online (Sandbox Code Playgroud)
我在 google 和 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)
Run Code Online (Sandbox Code Playgroud)
我已将其删除,autospec因为我不确定它在这种情况下能否正常工作。如果有效的话您可以尝试将其放回去。
另一种选择可能是使用patch()你得到的任何东西type(Note.objects)(可能是一些 django 类)。
正如我所说,我对 django 不太了解,所以我不确定这些东西是否有效。