【问题标题】:How to test a method decorated with @staff_member_required in class based views?如何在基于类的视图中测试用@staff_member_required 装饰的方法?
【发布时间】:2019-07-23 09:22:26
【问题描述】:

我有这样的看法:

class MyView:
    @staff_member_required 
    def post(self, request):
        #some logic

我正在使用 pytest https://pytest-django.readthedocs.io/en/latest/ 进行测试。

我试过了:


@pytest.mark.django_db
def test_upload_payments(rf):
    with open("tests/fixtures/test_payments.csv") as f:
        request = rf.post("/invoice_admin/upload_payments/",
                          {"invoice_file": f})

        resp = MyView().post(request)
        assert resp.status_code == 201 

但是,我得到一个错误:

request = <WSGIRequest: POST '/invoice_admin/upload_payments/'>, args = (), kwargs = {}

    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
>       if test_func(request.user):
E       AttributeError: 'WSGIRequest' object has no attribute 'user'

/usr/local/lib/python3.6/dist-packages/django/contrib/auth/decorators.py:20: AttributeError

如果我删除 @staff_member_requred,一切正常 - 测试按预期运行。

我该如何解决这个问题?

我并不真正关心成为具有正确测试凭据的管理员——我只想“强制登录”并能够运行测试。

【问题讨论】:

标签: python django pytest pytest-django


【解决方案1】:

According to pytest-django's doc,在你的情况下,rf 是一个 django RequestFactory 实例,所以你的问题是“使用 RequestFactory 时如何设置用户” - which is documented too:你只需要设置 request.user = some_user_object (其中some_user_object 可以是任何满足staff_member_required 装饰器需求的东西。

如何,是的:它是基于类的事实实际上完全无关紧要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2015-03-25
    • 2014-10-20
    • 1970-01-01
    • 2017-03-08
    • 2012-06-11
    相关资源
    最近更新 更多