0

I have a view like so:

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

I'm using pytest https://pytest-django.readthedocs.io/en/latest/ for testing.

I tried this:


@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 

However, i get an error:

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

If i remove @staff_member_requred, everything works fine - the test runs as expected.

How do I fix this?

I don't really care about being an admin with the right credentials for testing -- i just want to "force login" and be able to run the test.

nz_21
  • 6,140
  • 7
  • 34
  • 80

1 Answers1

2

According to pytest-django's doc, in your case, rf is a django RequestFactory instance, so your question is "how to set the user when using RequestFactory" - which is documented too: you just have to set request.user = some_user_object (where some_user_object can be anything that satisfies the staff_member_required decorator's needs).

How and yes: the fact it's a class-based is actually totally irrelevant.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118