所以我发现了这个问题: Django Rest Framework testing save POST request data
我知道只要功能正在运行,就可以访问用POST请求创建的数据。因此,我用一个函数进行了整个测试:
class PostMovieAPITest(APITestCase):
def test_correct_request(self):
title = 'Snatch'
response = self.client.post('/movies/', data={'title': title}, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
movies = Movie.objects.all()
self.assertTrue(Movie.objects.get(title=title))
问题是,即使我在同一函数中发送CREATE / POST请求,Movie.objects.all()
也为空。当我执行“ manage.py runserver”并在浏览器中对其进行测试时,API可以正常工作。但是如何编写适当的测试来检查数据是否确实保存在数据库中?
urls.py:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'movies', views.MovieViewSet)
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls),
]
views.py:
class MovieViewSet(viewsets.ModelViewSet):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
def create(self, request, *args, **kwargs):
title = request.data.get('title')
if not title:
return Response({'Error': "Body should be {'title':'The title of the Movie'}"}, status=status.HTTP_400_BAD_REQUEST)
data = get_data_from_omdb(title)
if len(data) == 0:
return Response({"Error": "Title does not exist in OMDB database"}, status=status.HTTP_400_BAD_REQUEST)
serializer = MovieSerializer(data=data, context={'request': request})
if serializer.is_valid(raise_exception=False):
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:1)
通过Ozgur Akcali的评论发现了问题。我无法获得电影,因为Movie对象是基于外部API的数据(包括标题)创建的。
“雇用 m e!” ->“雇 M e!”
有时候脚本使我想杀人。非常感谢,很抱歉浪费您的时间。
def test_correct_request(self):
title = 'Hire Me!' # was: 'Hire me!'
response = self.client.post('/movies/', data={'title': title}, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(Movie.objects.get(title=title))