Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 530
Purrell Avatar asked Jan 10 '10 05:01

Purrell


People also ask

What is mocking in Django?

When mocking in a test, we are in a certain way making fun of our software or of the function we are testing, simulating the behaviour of a specific external functionality. In Python there is a package in the standard library that helps us apply mocks during our tests.

Does Django come with requests?

Quick overview. Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request.

What is TestCase in Django?

TestCase. This test class creates a clean database before its tests are run, and runs every test function in its own transaction. The class also owns a test Client that you can use to simulate a user interacting with the code at the view level.


1 Answers

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)

like image 195
naoko Avatar answered Sep 21 '22 16:09

naoko