How to mock users and requests in django

Purrell picture Purrell · Jan 10, 2010 · Viewed 44.6k times · Source

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?

Answer

naoko picture naoko · Sep 14, 2014

For request, I would use RequestFactory included with Django.

from django.test.client import RequestFactory
rf = RequestFactory()
get_request = rf.get('/hello/')
post_request = rf.post('/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)