如何使用pytest-django编写正确的测试?

时间:2019-11-01 03:42:58

标签: django pytest pytest-django

我正在开始使用pytest。我尝试使用预定义的数据测试ListView,但是response.context_data ['object_list']为空。怎么了?

这是我的代码:

from http import HTTPStatus
from django.test import RequestFactory
from django.urls import reverse_lazy
from mixer.backend.django import mixer
import pytest

from career.constants import THREE_FIVE_YEARS
from career.constants import WITHOUT_EXPERIENCE
from career.models import Employment
from career.models import Schedule
from career.models import Vacancy
from career.views import VacancyList


pytestmark = pytest.mark.django_db(transaction=True)

class TestVacancyView:
    """Testing vacancy views."""

    list_url = 'vacancy_list'
    list_path = reverse_lazy(list_url)
    factory = RequestFactory()

    def test_list_get(self, client):
        first_schedule = Schedule.objects.first()
        last_schedule = Schedule.objects.last()
        employment_first = Employment.objects.first()
        employment_last = Employment.objects.last()
        mixer.blend(
            Vacancy, city='New York', salary_max=30000,
            experience=WITHOUT_EXPERIENCE, schedule=first_schedule,
            employment=employment_first
        )
        mixer.blend(
            Vacancy, city='London', salary_max=40000,
            experience=THREE_FIVE_YEARS, schedule=first_schedule,
            employment=employment_first
        )
        mixer.blend(
            Vacancy, city='New York', salary_max=50000,
            experience=THREE_FIVE_YEARS, schedule=last_schedule,
            employment=employment_last
        )

        request = self.factory.get(self.list_path)
        response = VacancyList.as_view()(request)
        assert response.context_data['object_list'].count() == 3    

我期望数据库中有3条记录,实际输出为0。但是当我在调试器中查询测试数据库时,数据存在。

0 个答案:

没有答案