我有一个 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/