我试图测试一些意见的网址,但似乎我被封锁与证书,我看到其他职位与同样的问题,并试图遵循他们,但我仍然作为理智点

test_web_share_file_folder_view_set. py

class WebShareFileFolderViewSetTestCase(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.user = User.objects.create_user(username='my_user', password='my_password')
        headers = web_backend_api_access_headers()
        self.token = headers['Authorization']
        self.client = APIClient()

    def test_list_with_search(self):
        WebShareFileFactoryBoy(name="file_with_search", path="path_with_search")

        url = reverse('web-share-file-folders-list')
        request = self.factory.get(url, {'search': 'file_with_search'})
        request.user = self.user

        self.client.credentials(HTTP_AUTHORIZATION='Bearer' + self.token)
        response = self.client.get(url,  headers={'Authorization': 'Bearer ' + self.token})
        print(response.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTrue('file_with_search' in response.data['results'][0]['name'])

下面是我开始测试时的错误

FAIL: test_list_with_search (tests.test_web_share_file_folder_view_set.WebShareFileFolderViewSetTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "-\tests\test_web_share_file_folder_view_set. py", line 32, in test_list_with_search
    self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 401 != 200

这里是响应的打印.data

{'detail': ErrorDetail(string='Need Authorization Header', code='authentication_failed')}

如果有人有一个 idea :? 谢谢你

解决方案:force_authenticate是解决方案

def test_of_BranchViewSet_with_delete_request(self):
    self.user = baker.make(User)
    url = reverse('branch-list')
    self.client.force_authenticate(user=self.user)
    response = self.client.delete(url)
    self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)

我try 访问视图进行测试

推荐答案

凭证方法可用于设置标头,然后测试客户端将包含在所有后续请求中.

from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

# Include an appropriate Authorization: header on all requests.
token = Token.objects.get(user__username='lauren')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

第二:

# Here user is my requested user and i'm forcefully authenticate user to make successfully requset.
self.client.force_authenticate(user=self.user)

完整的测试用例在这里:

def test_of_BranchViewSet_with_delete_request(self):
    self.user = baker.make(User)
    url = reverse('branch-list')
    self.client.force_authenticate(user=self.user)
    response = self.client.delete(url)
    self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)

参考编号:https://www.django-rest-framework.org/api-guide/testing/#headers-authentication

Django相关问答推荐

Django 5.0.2:TypeError:获取切片后无法过滤查询

POST_SAVE接缝有错误

Django中的判断约束

Django:作为模型中的列表元素的字段

在 Trunc 的 kind 属性中使用字段

获取 Django (postgres) 中带注释字段的平均值

如何使用邮箱确认码创建django注册

有谁知道是否可以将您的 Django Heroku 应用程序放到 App Store/Google Play 上?

NoneType对象没有属性保存Django

django - 表单没有错误,但 form.is_valid() 没有验证

Django 表单有 Select 但也有自由文本选项?

如何获得用户权限?

Django PositiveIntegerField 中的 0 值?

为什么 django 1.7 会为字段 Select 的变化创建迁移?

django- nginx: [emerg] open() "/etc/nginx/proxy_params" 在 /etc/nginx/sites-enabled/myproject:11 中失败(2:没有这样的文件或目录)

保存前向 ModelForm 对象添加数据

Django REST Framework - 序列化可选字段

Django 在 css 文件中使用背景图像的方法

XlsxWriter 对象另存为 http 响应以在 Django 中创建下载

何时使用 Django get_absolute_url() 方法?