request.user returns a SimpleLazyObject, how do I “wake” it?

后端 未结 6 1920
萌比男神i
萌比男神i 2020-12-05 03:57

I have the following method:

def _attempt(actor):
    if actor.__class__ != User:
        raise TypeError

Which is called from a view:

6条回答
  •  臣服心动
    2020-12-05 04:21

    For anyone wanting to write a failing "small" unittest for your code, you can generate a wrapped User and stuff it inside a request.

    from django.contrib.auth import get_user_model
    from django.test import RequestFactory
    from django.utils.functional import SimpleLazyObject
    
    user = get_user_model().objects.create_user(
        username='jacob',
        email='jacob@…',
        password='top_secret',
    )
    
    factory = RequestFactory()
    request = factory.get('/')
    request.user = SimpleLazyObject(lambda: user)
    

    See:

    • https://github.com/django/django/blob/master/tests/utils_tests/test_lazyobject.py for current tests on the Lazy Objects.

    • https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.RequestFactory for latest info on the RequestFactory.

提交回复
热议问题