python - 来自相关对象的 Django 单元测试模拟查询集

标签 python django unit-testing django-queryset django-testing

我有以下功能:

import unittest
from unittest import mock


def get_payments(order):
    return order.payments.filter(status='complete').order_by('-date_added)

我想模拟 filter 方法和 order_by 来检查调用的参数。

我试过:

class TestPayments(unittest.TestCase):
     @mock.patch('path.Order.payments.filter.order_by')
     @mock.patch('path.Order.payments.filter')
     def test_get_payments(self, mock1, mock2):
        mock1.assert_called_with(status='complete')
        mock2.assert_called_with('-date_added')

我试过的另一个模拟:

@mock.patch('path.Payment.objects.filter.order_by')
@mock.patch('path.Payment.objects.filter')

@mock.patch('path.Order.payments.objects.filter.order_by')
@mock.patch('path.Order.payments.objects.filter')

在最后两个模拟中,我有一个错误,即 path.Order 不存在。 我已经为 Payment.objects.filter() 这样的查询使用了直接模拟并且正在工作,但是从像 Order 这样的相关模型开始我失败了。

OrderPayment 之间的关系是您所期望的一对多关系。

最佳答案

通过模拟对象我解决了这个问题。

    order = MagicMock(side_effect=Order())
    order.payments.filter.return_value = MagicMock(side_effect=Payment.objects.filter(id=0))
    order.payments.filter.return_value.order_by.return_value = [Payment()]

    order.payments.filter.assert_called_with(status='complete')
    order.payments.filter.return_value.order_by.assert_called_with('-date_updated')

关于python - 来自相关对象的 Django 单元测试模拟查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47097803/

相关文章:

python - 在 matplotlib 中以特定角度绘制饼图,并在楔形上绘制分形

java - 哪些工具可用于将测试数据填充到 mongodb

c# - 无法从用法中推断出方法的类型参数

python - 未绑定(bind)的 super 对象,super(self, self)

python - 如何使用 selenium webdriver 和 python 关闭 chrome 浏览器弹出对话框

python - Django:按值过滤或返回所有记录

python - 值错误 : Unable to configure filter 'require_debug_false' : Cannot resolve 'django.utils.log.RequireDebugFalse' : No module named RequireDebugFalse

python - 根据计算值过滤 django 查询集

unit-testing - 如何使用 f# 编写带有模拟的测试

python - 我如何处理 Django 中的 spotify api 身份验证重定向 uri?