python - 使用Django Rest Framework的APITestCase时出错

标签 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)

我知道 View 本身有效,因为我单独测试了它。数据肯定存在,因为 helper.reset_test_db() 将其放在那里(我知道我应该使用固定装置,但这是为了测试,所以我采用了简单的路线)。 POST 和其他命令或者当我使用 Django 的 TestCase 而不是 APITestCase 时,也会发生相同的错误。虽然这是我第一次使用 Django 的 TestCase,但我阅读了 Django 和 Django Rest 文档,但似乎无法弄清楚这个问题。

最佳答案

您的案例中的 View 是基于类的 View 。

所以你必须使用as_view将其添加到urlconfig中:

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

关于python - 使用Django Rest Framework的APITestCase时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234443/

相关文章:

python - 在 Django Rest Framework Viewset 中添加计数对象

python - 按下拍摄按钮时控制拍摄频率?

Python:如果行中只有 1 个单词,则替换数据框/列中的字符串

python - 如何在没有服务器的情况下将 mlflow 指标和参数保存到 s3 存储桶?

python - Django Rest Framework 在序列化程序中获取用户

Django REST框架GET嵌套序列化器产生错误: 'RelatedManager' object has no attribute 'datafile_set' "

python - linux下通过脚本/命令行替换PE EXE文件中的资源

html - 当我需要从 WYSIWYG 编辑器呈现 HTML 时如何防止 XSS 攻击?

python - Django 中的查询集联合

Django:检查 Field 对象中的 ManyToManyField 是否为空