如何在基于类的视图中测试以@staff_member_required装饰的方法?

时间:2019-07-23 09:22:26

标签: python django pytest pytest-django

我有这样的看法:

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,一切都会正常-测试会按预期进行。

我该如何解决?

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

1 个答案:

答案 0 :(得分:2)

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装饰者的需求)。

方法和是:实际上,它是基于类的,实际上是完全不相关的。