How to mock users and requests in django


I have django code that interacts with request objects or user objects. For instance something like:

foo_model_instance = models.get_or_create_foo_from_user(request.user)

If you were going to test with the django python shell or in a unittest, what would you pass in there? Here simply a User object will do, but the need for a mock request object also comes up frequently.

For the shell or for unittests:

  • How do you mock users?
  • How do you mock requests?
1/10/2010 5:20:46 AM

Accepted Answer

For request, I would use RequestFactory included with Django.

from django.test.client import RequestFactory
rf = RequestFactory()
get_request = rf.get('/hello/')
post_request ='/submit/', {'foo': 'bar'})

for users, I would use django.contrib.auth.models.User as @ozan suggested and maybe with factory boy for speed (with factory boy you can choose to not to save to DB)

3/29/2016 2:39:28 PM

How do you mock users?

Initialise a django.contrib.auth.models.User object. User.objects.create_user makes this easy.

How do you mock requests?

Initialise a django.http.HttpRequest object.

Of course, there are shortcuts depending on what you want to do. If you just need an object with a user attribute that points to a user, simply create something (anything) and give it that attribute.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow