我正在尝试运行一些测试以配合Django REST教程(参见源代码(。我得到了一个使用 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
,但以当前形式失败,我基于 在 Django 测试框架中使用基本 HTTP 访问身份验证:
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
错误。关于如何解决这个问题的任何想法?
尝试:
self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials.decode('utf-8'))
或者,您也可以考虑这样做
我最终解决了这个问题,只需使用setUp
方法中定义的self.user
的username
和password
调用self.client
的login
方法:
import json
from django.contrib.auth.models import User
from django.test import TestCase
from rest_framework.test import APITestCase
from snippets.models import Snippet
class SnippetTestCase(APITestCase):
def setUp(self):
self.username = 'john_doe'
self.password = 'foobar'
self.user = User.objects.create_user(username=self.username, password=self.password)
def test_1(self):
self.client.login(username=self.username, password=self.password)
response = self.client.post('/snippets/', {'code': 'Foo Bar'}, format='json')
self.assertEqual(response.status_code, 201)
此测试通过:
Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.259s
OK
Destroying test database for alias 'default'...