Django 1.9.2测试客户端问题

时间:2016-02-26 20:16:00

标签: django django-rest-framework django-testing

我正在使用Django==1.9.2djangorestframework==3.3.2以及django.test.Client进行一些测试。问题是,当我执行测试时,我得到了这个错误:

ERROR: test_view (main.tests.test_http.TestMainViewSet)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/vladir/work/all/project-django1.9/saxo-publish/publish/main/tests/test_http.py", line 111, in test_view
    content_type='application/json'
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/test/client.py", line 515, in post
    secure=secure, **extra)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/test/client.py", line 314, in post
    secure=secure, **extra)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/test/client.py", line 380, in generic
    return self.request(**r)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/test/client.py", line 449, in request
    response = self.handler(environ)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/test/client.py", line 123, in __call__
    response = self.get_response(request)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 245, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 296, in handle_uncaught_exception
    return callback(request, **param_dict)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 166, in _wrapped_view
    return middleware.process_response(request, response)
  File "/home/vladir/work/all/project-django1.9/venv/local/lib/python2.7/site-packages/django/middleware/csrf.py", line 230, in process_response
    request.META["CSRF_COOKIE"],
KeyError: u'CSRF_COOKIE'

我的测试代码如下:

import json

from django.test import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User


class TestMainViewSet(TestCase):

    def setUp(self):
        self.client = Client(
            HTTP_HOST='example.com' # I have also tried removing this
        )
        self.create_read_url = reverse('books-list')
        User.objects.create_user(
            username="username",
            email="username@zunzun.se",
            password="123"
        ) 

    def test_create(self):
        self.client.login(username='username', password="123")
        # In this case I'm doing a POST, but it is the same with a GET
        response = self.client.post(
            self.create_read_url,
            data=json.dumps({'title': "Create"}), # I have also tried without the json.dumps
            content_type='application/json'
        )

        data = json.loads(response.content)
        print data

        self.assertEqual(response.status_code, 201)
        self.assertEquals(data['title'], "Create")

我的view代码是:

from django.contrib.auth.mixins import LoginRequiredMixin

from rest_framework import viewsets

from .serialiazers import (
    BookSerializerRead,
    BookSerializerWrite,
)

class MainViewSet(LoginRequiredMixin, viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class_read = BookSerializerRead
    serializer_class_write = BookSerializerWrite
<{1}}上的

urls.py

根据Django doc的说法,我不需要任何其他内容来避免from rest_framework import routers router = routers.DefaultRouter() router.register(r'books', MainViewSet, 'books') urlpatterns = [ url(r'^api/', include(router.urls)), ] , 因为在文本上说:&#34;默认情况下,测试客户端将禁用您网站执行的任何CSRF检查。&#34;,我也知道CSRF checks默认 在enforce_csrf_checks=False

我找到了一个细节,如果我以Client方式创建客户端实例然后它可以工作,但是 真的需要吗?这不是文档所说的,所以我想我做错了什么。有人可以帮帮我吗?我将不胜感激任何帮助。 提前致谢

1 个答案:

答案 0 :(得分:0)

尝试使用DRF的APITestCase作为测试用例的基类:

from rest_framework.testing import APITestCase

class TestMainViewSet(APITestCase):
    ...