【发布时间】:2013-08-02 06:50:14
【问题描述】:
我正在尝试为使用 Django REST 框架编写的 REST API 编写一些功能测试。不过,它对那个框架并不是很具体,因为它主要是通用的 Django 东西。
这就是我想做的事情
- 在测试类的
setUp方法中创建用户 - 使用测试客户端从 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