我在视图集中添加了一个方法,如下所示:
class CustomImageViewSet(viewsets.ModelViewSet):
queryset = CustomImage.objects.all()
serializer_class = CustomImageSerializer
lookup_field = 'id'
@action(detail=True, methods=['get'], url_path='sepia/')
def sepia(self, request, id):
# do something
data = image_to_string(image)
return HttpResponse(data, content_type="image/png", status=status.HTTP_200_OK)
由于它不是默认或覆盖的请求方法,我不确定如何继续为它编写测试。有什么建议吗?
答案 0 :(得分:2)
您不清楚测试应该测试什么,但您可以测试响应 status_code,例如:
def test_sepia_api():
api_client = APIClient()
response = api_client.get(path="{path_to_your_api}/sepia/")
assert response.status_code == 200
答案 1 :(得分:2)
我注意到你在使用 pytest。我假设你也有 pytest-django(它确实让一切变得更容易)。我喜欢使用请求工厂,因为如果您有身份验证需求,它通常会更快。
def test_me(self, user, rf):
view = CustomImageViewSet()
request = rf.get("")
request.user = user # If you need authentication
view.request = request
response = view.sepia(request, 123)
assert response.data == BLAH