【问题标题】:Writing functional tests for Django RESTful API为 Django RESTful API 编写功能测试
【发布时间】:2013-08-02 06:50:14
【问题描述】:

我正在尝试为使用 Django REST 框架编写的 REST API 编写一些功能测试。不过,它对那个框架并不是很具体,因为它主要是通用的 Django 东西。

这就是我想做的事情

  1. 在测试类的setUp方法中创建用户
  2. 使用测试客户端从 API 请求用户令牌

tests.py

from django.test import LiveServerTestCase

from django.contrib.auth.models import User
from django.test.client import Client
from rest_framework.authtoken.models import Token

class TokenAuthentication(LiveServerTestCase):
    def setUp(self):
        user = User.objects.create(username='foo', password='password', email="foo@example.com")
        user.save()
        self.c = Client()

    def test_get_auth_token(self):
        user = User.objects.get(username="foo")
        print user # this outputs foo
        print Token.objects.get(user_id = user.pk) # this outputs a normal looking token
        response = self.c.post("/api-token-auth/", {'username': 'foo', 'password': 'password'})
        print response.status_code # this outputs 400
        self.assertEqual(response.status_code, 200, "User couldn't log in")

当我运行测试时,它返回状态 400 而不是 200,因此用户未通过身份验证。如果我在数据库中输入用户的凭据,它会通过。所以我假设在测试类中创建的记录只能在它自己的方法中访问,这可能是因为它是为单元测试而设计的。但是我使用数据库中的数据来执行测试,如果数据发生变化,它会失败。

这样的功能测试,在运行测试之前需要创建数据,应该如何在 Django 中执行?

【问题讨论】:

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


    【解决方案1】:

    您创建的用户不正确。 User.objects.create 以纯文本而不是通过散列机制设置密码。您应该改用User.objects.create_user,它将正确设置密码,以便您可以使用用户名和密码进行身份验证。

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多