如何测试是否调用了Django QuerySet方法?

2024-04-23 20:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下几点:

models.py

class FooQuerySet(models.QuerySet):

    def bar(self):
        return self.filter(...)


class Foo(models.Model):
    ...

    objects = models.Manager.from_queryset(FooQuerySet)

views.py

class FooListView(ListView):
    model = Foo

    def get_queryset(self):
        qs = super().get_queryset()

        return qs.bar()

我希望测试在调用视图时调用models.FooQuerySet.bar。你知道吗

到目前为止,我已经:

request = RequestFactory().get('')
view = FooListView.as_view()

with mock.patch('<best_guess>') as mocked:
    mocked.return_value = Foo.objects.none()
    view(request)
    mocked.assert_called_once()

其中<best_guess>已经:

  • foo_app.models.FooQuerySet.bar
  • foo_app.models.Foo.objects.bar
  • foo_app.views.Foo.objects.bar

这些都不管用。即使我碰巧发现了一个神奇的补丁串,它确实起了作用,我恐怕我根本不明白这里发生了什么。测试FooQuerySet.bar()的正确方法是什么?你知道吗

(还有一个额外的困难是查询集是链接的,所以有一天我可能需要知道是否调用了FooQuerySet.any().amount().of().weird().methods().bar())。你知道吗


Tags: pyselfviewappgetreturnobjectsfoo
1条回答
网友
1楼 · 发布于 2024-04-23 20:32:20

我会试图模仿ListView.get_queryset,并将其保留为MagicMock,例如:

with mock.patch("foo_app.views.ListView.get_queryset") as mocked:
    view(request)
    mocked.bar.assert_called_once()

对于长链回调,只需使用:

mocked.bar.return_value.any.return_value.amount.return_value.of.assert_called_once()
...

但是,请记住,如果视图依赖于返回的QuerySet,那么在使用MagicMock实例呈现时可能会引发一些错误。你知道吗

相关问题 更多 >