python - 如何使用 PyTest 正确测试 Django API ListView?

标签 python django django-rest-framework pytest pytest-django

我有一个 API ListView 端点,当我用 Postman 拍摄它时它可以正常工作,但在测试中返回空查询集和状态 404:

测试结果:

web_1  | >       assert response.status_code == 200
web_1  | E       assert 404 == 200

我使用 pytest fixture 来创建我的对象:

conftest.py


@pytest.fixture
def event(system, new_conflict):
    return Event.objects.create(
        system=system,
        event_type='new_conflict',
        details=new_conflict
    )

fixture 在其他(非 API)测试中工作正常,所以我相信问题可能出在我测试 API 的方式上。在pycharm调试器中我可以看到 View 被执行,所以这不是url问题。

在 postman 中,此端点正确返回带有事件对象和状态 200 的 json。

test_api.py


from rest_framework.test import APIClient

from event_finder.models import Event
import pytest


@pytest.mark.django_db
def test_list_events_all(event):
    client = APIClient()
    response = client.get(path='/api/events/', format='json')

    assert response.status_code == 200

views.py

from rest_framework.generics import ListAPIView

from event_finder.models import Event
from event_finder.serializers import EventSerializer


class ListView(ListAPIView):
    queryset = Event.objects.all()
    serializer_class = EventSerializer

最佳答案

这是一个非常简单的例子。但也许你可以让它像这样工作:

from rest_framework.test import APITransactionTestCase
from rest_framework.test import status

class TestThis(APITransactionTestCase):
    def test_this(self):
        data = {"key": "value"}
        response = self.client.post("/api/resource", data=data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

希望对您有帮助。

关于python - 如何使用 PyTest 正确测试 Django API ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59387250/

相关文章:

php - Django Facebook 库

python - 如何平滑Python中的数据?

python - 如何使用 PyEnchant 更正文本并自动返回更正后的文本

python - 带有 smtp.gmail SMTPAuthenticationError 534 的 Django 电子邮件需要特定于应用程序的密码

python - 如何使用 python django 在 html 中显示图像?

django - CORS 在 dockerized Django REST + Angular 项目中被阻止

python - 如何复制字典并仅编辑副本

python - 使用 Django 查询 Neo4j 数据库

python - 大型 django rest 框架应用程序的目录结构

python - 如何卸载 django-rest-swagger?