Django unittest过滤功能

Django unittest the filter function

我有以下问题:

class Foo(models.Model):
    bars = models.ManyToMany(Bar)

# in a function somewhere else
def bla(bars):
    return Foo.objects.filter(bars__in=bars)

我想测试在调用 bla() 时是否使用给定参数调用了 .filter()

我是这样写测试的:

@patch('my_module.models.Foo')
def test_bla(self, FooMock):
    Foo.objects.filter = Mock()
    foo([1, 2])
    Foo.objects.filter.assert_called_with(bars__in=[1, 2])

失败 Not called。不确定我是否做对了。有人可以帮我正确地做吗?

谢谢!

我认为问题出在您修补的地方。我认为这会很好地引导您解决问题:

http://alexmarandon.com/articles/python_mock_gotchas/