使用Pytest和Mock来测试查询数据库的视图

时间:2015-08-27 14:29:29

标签: python django unit-testing mocking pytest

我试图为我的Django应用程序使用的视图编写单元测试。视图本身通过自定义模型(下面视图的代码片段)从数据库中获取数据。

views.py

def calibrator_data(calid,code):
    data = []
    sources, times = zip(*DataSource.objects.filter(event__name=code).values_list('id','timestamp').order_by('timestamp'))
    points  = Datapoint.objects.filter(data__in=sources)
    people = Decision.objects.filter(source__id=calid,planet__name=code,value='D',current=True).values_list('person__username',flat=True).distinct()
    norm = dict((key,0) for key in sources)
    for pid in people:
        cal = []
        sc = dict(points.filter(user__username=pid,pointtype='S').values_list('data__id','value'))
        bg = dict(points.filter(user__username=pid,pointtype='B').values_list('data__id','value'))
        c = dict(points.filter(user__username=pid,pointtype='C',coorder__source__id=calid).values_list('data__id','value'))
        sc_norm = dict(norm.items() + sc.items())
        bg_norm = dict(norm.items() + bg.items())
        c_norm = dict(norm.items() + c.items())
        for v in sources:
            try:
                cal.append((sc_norm[v]- bg_norm[v])/(c_norm[v] - bg_norm[v]))
            except:
                cal.append(0)
        data.append(cal)
    return data,[timegm(s.timetuple())+1e-6*s.microsecond for s in times],list(people)

我试图写的测试。

test_reduc.py

pytestmark = pytest.mark.django_db

@pytest.mark.django_db
class TestDataReduction(TestCase):

    pytestmark = pytest.mark.django_db

     ################################################################################
     ############################ Testing calibrator_data ###########################
     ################################################################################

    def test_calibrator_data(self):

        mock_source = MagicMock(spec=DataSource)
        mock_times = MagicMock(spec=DataSource)
        mock_source.return_value = array([random.randint(0,10)])
        mock_times.return_value = datetime.now()

        mock_points = MagicMock(spec=Datapoint)
        mock_points.user = []

        mock_people = MagicMock(spec=Decision)
        mock_people.data = []

        calid = 22
        code = 'corot2b'

        self.output = calibrator_data(calid,code)

        assert type(self.output[0])==type([])

测试因错误而失败:

    =============================================== test session starts ===============================================
platform darwin -- Python 2.7.10 -- py-1.4.30 -- pytest-2.7.2
rootdir: /Users/tomasjames/Documents/citsciportal/app, inifile: pytest.ini
plugins: django
collected 1 items 

agentex/tests/test_reduc.py F

==================================================== FAILURES =====================================================
_____________________________________ TestDataReduction.test_calibrator_data ______________________________________

self = <agentex.tests.test_reduc.TestDataReduction testMethod=test_calibrator_data>

    def test_calibrator_data(self):

        mock_source = MagicMock(spec=DataSource)
        mock_times = MagicMock(spec=DataSource)
        mock_source.return_value = array([random.randint(0,10)])
        mock_times.return_value = datetime.now()

        mock_points = MagicMock(spec=Datapoint)
        mock_points.user = []

        mock_people = MagicMock(spec=Decision)
        mock_people.data = []

        calid = 22
        code = 'corot2b'

>       self.output = calibrator_data(calid,code)

agentex/tests/test_reduc.py:51: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

calid = 22, code = 'corot2b'

    def calibrator_data(calid,code):
        data = []
>       sources, times = zip(*DataSource.objects.filter(event__name=code).values_list('id','timestamp').order_by('timestamp'))
E       ValueError: need more than 0 values to unpack

agentex/datareduc.py:56: ValueError
============================================ 1 failed in 7.69 seconds =============================================

这是我第一次尝试编写任何类型的测试(你可能已经看到了)并且它是一个具有挑战性的测试。我认为错误是因为 views.py 仍在尝试访问测试环境中的数据库(使用空白数据库运行) - 时间似乎证实了这一点。我嘲笑变量来源,时间,点和人的尝试似乎并没有起作用。我试图将它们分配给我知道数据库查询产生的变量,以节省必须模拟整个数据库/ QuerySet。

这是不正确的实施测试方式吗?我无法发现我出错的地方。

提前致谢!

1 个答案:

答案 0 :(得分:1)

你错过了使用mock来覆盖方法的一个关键组件。你需要使用mock作为方法装饰器来基本上匹配你的方法,以便能够做你想做的事。

你想要写一些看起来像这样的东西。 (注意:根本没有对此进行过测试,但应该引导您朝着正确的方向前进。)

@pytest.mark.django_db
class TestDataReduction(TestCase):

    @mock.patch(your_module.xyz.DataSource)
    @mock.patch(your_module.xyz.Datapoint)
    @mock.patch(your_module.xyz.Decision)
    def test_calibrator_data(self, mock_source, mock_points,
                             mock_people):

        mock_source.objects.filter.return_value.values.return_value.order_by.return_value = [array([random.randint(0,10)]), datetime.now()]

        mock_points.objects.filter.return_value = []

        mock_people.objects.filter.values_list.return_value.distinct.return_value = []

        calid = 22
        code = 'corot2b'

        self.output = calibrator_data(calid,code)

        assert type(self.output[0])==type([])

您还需要模拟出任何您希望返回值为points.filter的多次调用。一种方法是使用副作用。这里有一个很好的例子:https://stackoverflow.com/a/7665754/2022511

除了我已经查看过的帖子(https://www.chicagodjango.com/blog/quick-introduction-mock/)之外,还有更多关于在此博文中使用mock.patch的信息:http://fgimian.github.io/blog/2014/04/10/using-the-python-mock-library-to-fake-regular-functions-during-tests/