python - 使用 Pytest 和 Mock 测试查询数据库的 View

标签 python django unit-testing mocking pytest

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

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 仍在尝试访问测试环境中的数据库(使用空白数据库运行) - 计时似乎证实了这一点。然而,我试图 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/

关于python - 使用 Pytest 和 Mock 测试查询数据库的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32252162/

相关文章:

python - ScrapyJS - 如何正确等待页面加载?

Java 相当于 python 的 getattr?

python - 模块 'importlib._bootstrap' 没有属性 '_w_long'

python - Django sqlmigrate 不显示原始 sql

java - Mockito 问题 - excepts.verification.WantedButNotInvoked

python - 属性始终为 None

python - 有没有内置的方法来定义一个接受 1 个参数或 3 个参数的函数?

Django:查询用户所属组的过滤器

reactjs - 使用 Jest 和 react 测试库进行单元测试自定义 Hook

java - JUnit 5 中的 @TestInstance 注释有什么用?