【发布时间】:2018-07-04 04:58:01
【问题描述】:
我正在尝试运行一些测试以配合 Django REST 教程(请参阅 source code)。我得到了一个使用APIClient 的.force_authenticate 方法的解决方案,但我更愿意更明确地构建凭据。我尝试了以下方法:
import json
import base64
from django.contrib.auth.models import User
from django.test import TestCase
from rest_framework.test import APITestCase, force_authenticate
from snippets.models import Snippet
class SnippetTestCase(APITestCase):
def setUp(self):
self.username = 'john_doe'
self.password = 'foobar'
self.user = User.objects.create(username=self.username, password=self.password)
# self.client.force_authenticate(user=self.user)
credentials = base64.b64encode(f'{self.username}:{self.password}'.encode('utf-8'))
self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials))
def test_1(self):
response = self.client.post('/snippets/', {'code': 'Foo Bar'}, format='json')
self.assertEqual(response.status_code, 201)
这个测试通过了 .force_authenticate 的注释行,但以我基于 Using Basic HTTP access authentication in Django testing framework 的当前形式失败:
Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_1 (tutorial.tests.SnippetTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1
self.assertEqual(response.status_code, 201)
AssertionError: 403 != 201
----------------------------------------------------------------------
Ran 1 test in 0.022s
FAILED (failures=1)
显然,身份验证不起作用,因为我收到了 403 Forbidden 错误。有关如何解决此问题的任何想法?
【问题讨论】:
-
你做得对。但是你确定标题是“Basic ...”吗?您可以发布您的身份验证课程吗?