python - 我可以在 Django 测试中避免 permission_required 装饰器吗?

标签 python django testing

我正在测试一组广泛使用“permission_required”装饰器的 Django 应用程序。在我所拥有的大多数 View 中,这源自 302 HTTP 响应。

我的问题是:有什么方法可以避免或停用测试中的“permission_required”,这样我在调用我的 View 时可以获得 200 响应,而不是 302?

谢谢!

最佳答案

只需在您的测试用例设置方法中使用 super 用户登录


from django.test import TestCase
from django.contrib.auth.models import User

class TestThatNeedsLogin(TestCase):
    def setUp(self):
        User.objects.create_superuser(
            'user1',
            'user1@example.com',
            'pswd',
        )
        self.client.login(username="user1", password="pswd")

    def tearDown(self):
        self.client.logout()

    def test_something(self):
        response = self.client.get("/")
        self.assertEqual(200, response.status_code)

关于python - 我可以在 Django 测试中避免 permission_required 装饰器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6772676/

相关文章:

python - 记录函数时如何引用 "True-like"和 "False-like"?

python - 在 ubuntu 上运行 dockerfile 时 django 安装失败

python - 当有很多字段时管理django的create方法

unit-testing - 如何在karma中模拟模拟服务失败?

c# - 为什么在使用 NET40-NoCaSTLe 时会出现 'Moq.Proxy.CaSTLeProxyFactory' 类型初始化程序异常?

python - 用什么来替换 python 中的接口(interface)/协议(protocol)

python - 如何使 Django sessionId cookie 安全

python - 有没有办法根据值查询Django中的枚举类型?

java - 使用 Java 邮件服务器进行测试

Python 应用引擎 put(self) :