我正在使用restframeworks测试模块来编写测试。我需要测试一个get请求,我为此创建了一个测试,如下所示
class BlogCommentTest(APISimpleTestCase):
def test_3002_getting_reviewcomment(self):
factory = APIRequestFactory()
request = factory.get(reverse('get-review-comments'), data= {"article": 1})
request.user = self.user
view = ReviewCommentViewSet.as_view({'get': 'list'})
force_authenticate(request, self.user)
response = view(request)
然而,当我想填充request.DATA时,我写的方式会填充request.GET和{'article':1}。使request.DATA以我想要的方式填充请求对象的正确方法是什么?
修改 viewset的代码是
class ReviewCommentViewSet(viewsets.ModelViewSet):
"""
viewset to get recursive serialized results
"""
model = models.ReviewComments
serializer_class = serializers.ReviewCommentSerializer
queryset = models.ReviewComments.objects.filter(is_deleted=False)
def serialize_tree(self, queryset):
"""
:return: A helper function to get list of next set of childrens
"""
for obj in queryset:
data = self.get_serializer(obj).data
data['parent'] = self.serialize_tree(obj.children.all().exclude(is_deleted=True))
yield data
def list(self, request):
queryset = self.get_queryset().filter(parent=None, article=request.DATA['article'])
data = self.serialize_tree(queryset)
return Response(data)
def retrieve(self, request, pk=None):
self.object = self.get_object()
data = self.serialize_tree([self.object])
return Response(data)