如何测试而不打数据库

时间:2018-02-10 14:39:33

标签: python django pytest

我想在没有访问数据库并使用pytest和pytest-mock的情况下测试此代码:

from django.db.model import Q
from orders.models import Order


def get_orders_without_comment():    
    return Order.objects.filter(Q(comment__exact='') | Q(comment__isnull=True}))

这是我的测试:

import pytest
from django.db.models import Q
from pytest_mock import mocker
from .utils import get_orders_without_comment

def test_get_orders_without_comment(mocker):
    orders_mock = mocker.patch('orders.models.Order.objects')

    orders = get_orders_without_comment()

    orders_mock.filter.assert_called_with(Q(comment__exact='') | Q(comment__isnull=True))

这是pytest例外:

E       AssertionError: Expected call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>)
E       Actual call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>)
E
E       pytest introspection follows:
E
E       Args:
E       assert (<Q: (OR: ('p...ll', True))>,) == (<Q: (OR: ('pi...ll', True))>,)
E         At index 0 diff: <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> != <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>
E         Use -v to get the full diff

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我已通过此代码解决了该问题:

def test_get_orders_without_comment(mocker):
    orders_mock = mocker.patch('orders.models.Order.objects')

    orders = get_orders_without_comment()

    q1 = orders_mock.filter.call_args[0][0]
    q2 = Q(comment__exact='') | Q(comment__isnull=True)
    assert str(q1) == str(q2)