使用Django Rest Framework APITestCase时出错

时间:2014-03-06 19:47:12

标签: python django django-rest-framework

我试图为我的Django-Rest-Framework API运行一些测试,但我遇到了错误。当我运行以下测试时,我会收到以下错误。

Traceback (most recent call last):
  File "C:\Users\Bill\SD\DjangoApps\vidapp\startapp\tests.py", line 21, in test_get_user
    response = self.client.get('/user/1/')
  File "C:\Anaconda\lib\site-packages\django\test\client.py", line 473, in get
    response = super(Client, self).get(path, data=data, **extra)
  File "C:\Anaconda\lib\site-packages\django\test\client.py", line 280, in get
    return self.request(**r)
  File "C:\Anaconda\lib\site-packages\rest_framework\test.py", line 143, in request
    return super(APIClient, self).request(**kwargs)
  File "C:\Anaconda\lib\site-packages\rest_framework\test.py", line 95, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "C:\Anaconda\lib\site-packages\django\test\client.py", line 444, in request
    six.reraise(*exc_info)
  File "C:\Anaconda\lib\site-packages\django\core\handlers\base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)

测试案例:

class UserTestCase(APITestCase):
    def setUp(self):
        helper.reset_test_db()

    def test_get_user(self):
        response = self.client.get('/user/1/')
        print response.content
        self.assertEqual(response.data, {'fname':'Generic','lname':'Name','token':'token1'})

网址配置:

url(r'^user/new/$', 'startapp.views.new_user'),
url(r'^user/1/$', 'startapp.views.get_1'),

查看:

class get_1(APIView):
    def get(self, request):
        user = db_models.User.objects.get(pk=1)
        if(user is not None):
            serial_user = serial.UserSerializer(user)
            return Response(serial_user.data)
        else:
            return Response(status.HTTP_404_NOT_FOUND)

我知道视图本身有效,因为我单独测试了它。数据肯定存在,因为helper.reset_test_db()把它放在那里(我知道我应该使用灯具,但这是用于测试所以我选择了简单的路线)。 POST和其他命令出现相同的错误,或者当我使用Django的TestCase而不是APITestCase时。虽然这是我第一次使用Django的TestCase,但我读了Django和Django的休息文档,但似乎无法弄清楚这个问题。

1 个答案:

答案 0 :(得分:3)

您的案例中的视图是基于类的视图。

因此您必须使用as_view将其添加到urlconfig:

url(r'^user/1/$', startapp.views.get_1.as_view()),