在 Django 测试框架中使用基本 HTTP 访问身份验证

发布于 2024-10-27 23:34:28 字数 114 浏览 2 评论 0原文

对于我的一些 Django 视图,我创建了一个执行基本 HTTP 访问身份验证的装饰器。然而,在 Django 中编写测试用例时,我花了一段时间才弄清楚如何对视图进行身份验证。我是这样做的。我希望有人觉得这很有用。

For some of my Django views I've created a decorator that performs Basic HTTP access authentication. However, while writing test cases in Django, it took me a while to work out how to authenticate to the view. Here's how I did it. I hope somebody finds this useful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

执手闯天涯 2024-11-03 23:34:28

我是这样做的:

from django.test import Client
import base64
auth_headers = {
    'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('username:password'),
}
c = Client()
response = c.get('/my-protected-url/', **auth_headers)

注意:您还需要创建一个用户。

Here's how I did it:

from django.test import Client
import base64
auth_headers = {
    'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('username:password'),
}
c = Client()
response = c.get('/my-protected-url/', **auth_headers)

Note: You will also need to create a user.

没有伤那来痛 2024-11-03 23:34:28

在 Django TestCase 中,您可以更新客户端默认值以包含您的 HTTP 基本身份验证凭据。

import base64
from django.test import TestCase

class TestMyStuff(TestCase):

    def setUp(self):
        credentials = base64.b64encode('username:password')
        self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + credentials

In your Django TestCase you can update the client defaults to contain your HTTP basic auth credentials.

import base64
from django.test import TestCase

class TestMyStuff(TestCase):

    def setUp(self):
        credentials = base64.b64encode('username:password')
        self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + credentials
折戟 2024-11-03 23:34:28

对于 python3,您可以对 username:password 字符串进行 Base64 编码:

base64.b64encode(b'username:password')

这会返回字节,因此您需要使用 .decode('ascii') 将其转换为 ASCII 字符串:

完整示例:

import base64

from django.test import TestCase

class TestClass(TestCase):
   def test_authorized(self):
       headers = {
           'HTTP_AUTHORIZATION': 'Basic ' + 
                base64.b64encode(b'username:password').decode("ascii")
       }
       response = self.client.get('/', **headers)
       self.assertEqual(response.status_code, 200)

For python3, you can base64-encode your username:password string:

base64.b64encode(b'username:password')

This returns bytes, so you need to transfer it into an ASCII string with .decode('ascii'):

Complete example:

import base64

from django.test import TestCase

class TestClass(TestCase):
   def test_authorized(self):
       headers = {
           'HTTP_AUTHORIZATION': 'Basic ' + 
                base64.b64encode(b'username:password').decode("ascii")
       }
       response = self.client.get('/', **headers)
       self.assertEqual(response.status_code, 200)
梦冥 2024-11-03 23:34:28

假设我有一个登录表单,我使用以下技术通过测试框架登录:

    client = Client()
    client.post('/login/', {'username': 'john.smith', 'password': 'secret'})

然后我在其他测试中携带客户端,因为它已经过身份验证。您对这篇文章有什么疑问?

Assuming I have a login form, I use the following technique to login through the test framework:

    client = Client()
    client.post('/login/', {'username': 'john.smith', 'password': 'secret'})

I then carry the client around in my other tests since it's already authenticated. What is your question to this post?

柠檬色的秋千 2024-11-03 23:34:28

(python3)我在测试中使用它:

credentials_string = '%s:%s' % ('invalid', 'invalid')
credentials = base64.b64encode(credentials_string.encode())
self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + credentials.decode()

并在视图中使用以下内容:

import base64
[...]
type, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
auth = base64.b64decode(auth.strip()).decode()

(python3) I'm using this in a test:

credentials_string = '%s:%s' % ('invalid', 'invalid')
credentials = base64.b64encode(credentials_string.encode())
self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + credentials.decode()

and the following in a view:

import base64
[...]
type, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
auth = base64.b64decode(auth.strip()).decode()
喵星人汪星人 2024-11-03 23:34:28

另一种方法是绕过 Django Client() 并使用 Requests 代替。

class MyTest(TestCase):
    def setUp(self):
        AUTH = requests.auth.HTTPBasicAuth("username", "password")

    def some_test(self):
        resp = requests.get(BASE_URL + 'endpoint/', auth=AUTH)
        self.assertEqual(resp.status_code, 200)

Another way to do it is to bypass the Django Client() and use Requests instead.

class MyTest(TestCase):
    def setUp(self):
        AUTH = requests.auth.HTTPBasicAuth("username", "password")

    def some_test(self):
        resp = requests.get(BASE_URL + 'endpoint/', auth=AUTH)
        self.assertEqual(resp.status_code, 200)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文