django - 测试 protected View - 处理 PermissionDenied 响应

标签 django testing pytest

我正在尝试测试 protected View 。未经身份验证的用户将重定向到登录页面。当我运行测试时,它引发了 django.cose.exceptions.PermissionDenied,这是正常的,但我如何在不失败的情况下编写它,我如何测试重定向是否正确?

这是我所做的。


class TestProtectedRegistrationListView:
    """
    Verify registration views are protected from unauthenticated access.
    """

    def test_access_url(
        self, user: settings.AUTH_USER_MODEL, request_factory: RequestFactory
    ):
        view = RegistrationListView.as_view()
        request = request_factory.get("/admin_staff/registrations")
        request.user = user
        resp = view(request)
        assert resp == PermissionDenied

最佳答案

这是感兴趣的解决方案(@wencakisa 正确建议):


def test_authenticated_non_staff(self, rf):
    req = rf.get(reverse("dashboard.staff:lang-create"))
    user = UserFactory()
    assert False is user.is_staff
    req.user = user

    with pytest.raises(PermissionDenied):
        views.LangCreateView.as_view()(req)

为了记忆和回答我自己的愚蠢评论,测试响应 status_code 没有任何意义,因为我们引发了异常。

关于django - 测试 protected View - 处理 PermissionDenied 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55797073/

相关文章:

python - Django 应用程序覆盖和导入路径?

python - Django vs Python2.7 单元测试测试用例?

python - 在 django View 之外使用 session

python - 使用 South AND django 1.7 迁移的可重用应用程序的升级路径

javascript - 使用 Mocha 测试 Promises 时,如何在发生错误时打印完整的堆栈跟踪

testing - 不使用 Camel-Case 创建 Fitnesse 页面

api - 数据可视化API

python - 功能记录器在 Pytest 中引发 FileNotFoundError

python - py.test : Run initialization method before pytest_generate_tests

django - pytest-cov 一次涵盖许多应用程序