Django REST测试忽略了工厂的URL

时间:2016-04-20 12:33:27

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

我为Django REST视图编写APITestCase时遇到了一个奇怪的错误。

这是我的代码:

class CreateUserTest(APITestCase):
    def setup(self):
        self.superuser = User.objects.create_superuser('vishnu@vishnu.com', '1989-10-06', 'vishnupassword')
        self.client.login(username='vishnu', password='vishnupassword')
        self.data = a bunch of trivial data

    def test_can_create_user(self):
        print "create user"
        self.setup()
        self.token = Token.objects.get(user_id=self.superuser.id)
        self.api_key = settings.API_KEY
        self.factory = APIRequestFactory()
        self.request = self.factory.post('/api/v1/uaaaaaasers/?api_key=%s' % self.api_key,
                                    self.data,
                                    HTTP_AUTHORIZATION='Token {}'.format(self.token))
        force_authenticate(self.request, user=self.superuser)
        self.view = UserList.as_view()
        self.response = self.view(self.request)
        self.response.render()
        #print self.response.content
        self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

如你所见,我运行了一个工厂。对于故意错误的网址/ api / v1 / uaaaaaasers /

但测试没有抱怨:

Creating test database for alias 'default'... 
create user .
---------------------------------------------------------------------- 

Ran 1 test in 0.199s

OK Destroying test database for alias 'default'...

它不应该与错误的网址崩溃吗?我怎么知道测试结果正常?

2 个答案:

答案 0 :(得分:1)

如果您要测试向无效网址发布请求,请使用test client代替请求工厂。

class CreateUserTest(APITestCase):

    def test_can_create_user(self):
       ...
       response = self.client.post(
           '/api/v1/uaaaaaasers/?api_key=%s' % self.api_key,
           self.data,
           ...
       )
       ...

答案 1 :(得分:1)

你测试的都错了...... 您测试的响应来自直接视图调用...

self.view = UserList.as_view()
self.response = self.view(self.request)
self.response.render()
    #print self.response.content
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

您的上述案例将始终调用视图...

在实际的测试用例中,我们使用客户端访问URL并测试该响应

self.response = self.client.post('/api/v1/uaaaaaasers/?api_key=%s' % self.api_key,
                                self.data,
                                HTTP_AUTHORIZATION='Token {}'.format(self.token))
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)