【问题标题】:Django unittest the filter functionDjango unittest 过滤功能
【发布时间】:2015-12-01 14:05:22
【问题描述】:

我有以下问题:

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 失败。不确定我是否做得正确。有人可以帮我以正确的方式做吗?

谢谢!

【问题讨论】:

    标签: django python-3.x mocking python-unittest


    【解决方案1】:

    我相信问题出在你正在修补的地方。我认为这可以很好地引导您解决问题:

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

    【讨论】:

    • 非常感谢!我的测试仍然失败,但现在补丁正在运行。对于其他有同样问题的人:bla() 方法位于一个名为“过滤器”的模块中。当我执行@patch('filters.Foo') 时,补丁就会起作用。但是您可以阅读亚当发​​布的文章;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多