繁体   English   中英

在 Locust 上测试 DRF 端点时获取“未提供身份验证凭据”

[英]Getting "Authentication Credentials Were not Provided" when testing DRF endpoint on Locust

我正在尝试对允许用户使用 locust 创建帖子的端点进行负载测试,值得一提的是,用户在访问此端点之前需要经过身份验证。

问题:当我使用蝗虫访问端点时,我不断收到错误消息“未提供提供的身份验证”,尽管我已经这样做了,而且我还配置了我的端点以接受令牌(我使用的是默认的 DRF 令牌功能)。 知道我做错了什么吗? 任何帮助将不胜感激。 下面是我的代码:

蝗虫档案

class ListPostUser(HttpUser):
    wait_time = between(1, 5)

    @task(3)
    def create_post(self):
        data = {
            "title": "This is another random title", 
            "body": "This is the body of a randomly titled post"
        }
        headers = {
            "Authorization": "Token 508e650b0ca1613818939089190a1661a75865b1"
        }
        response = self.client.post("blog/create", json=data, headers=headers)

        print(response)
        print(response.json())

    @task
    def comment_detail(self):
        self.client.get("blog/comment/1")

    @task(2)
    def post_detail(self):
        self.client.get("blog/post/1")


    def on_start(self):
        self.client.post("login/", json={"username": "username", "password": "mypassword"})

查看文件

class CreatePostAPI(APIView):
    permission_classes = (IsAuthenticated, )
    
    def post(self, request):
        serializer = CreatePostSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=self.request.user)
            return Response(serializer.data, status=status.HTTP_200_OK)

我还应该注意端点在 POSTMAN 上工作正常,我只在使用 Locust 进行负载测试时才收到错误

不确定这是否会帮助您找到真正的问题,但您可以通过检查response.request来调查发送的确切负载,如下所示:

print(response.request.headers) print(response.request.data)

我终于找到了解决问题的方法,我需要做的就是将TokenAuthentication添加到 settings.py 文件中的默认身份验证类列表中

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': 
    [
        'rest_framework.authentication.TokenAuthentication',
        ...
    ],
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM