How to mock users and queries in django

I have django code that interacts with request objects or user objects. For example, for example:

foo_model_instance = models.get_or_create_foo_from_user(request.user) 

If you were going to test python django shell or unittest, what would you go there? A User object will simply be created here, but often there is a need for a mock request object.

For shell or for unittests:

  • How do you mock users?
  • How do you mock requests?
+48
python django unit-testing mocking
Jan 10 '10 at 5:20
source share
5 answers

For the request, I used RequestFactory included in 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 possibly with a factory boy for speed (with a factory boy that you can not save to the database)

+45
Sep 14 '14 at 16:24
source share

How do you mock users?

Initialize the django.contrib.auth.models.User object. User.objects.create_user makes this easy.

How do you mock requests?

Initialize the django.http.HttpRequest object.

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

+38
Jan 10 '10 at 9:59
source share

Read about mock objects here.
http://en.wikipedia.org/wiki/Mock_object
http://www.mockobjects.com/

And use this python library to mock user
http://python-mock.sourceforge.net/

you can also write a simple user class yourself, use this as a starting point

 class MockUser(object): def __call__(self, *args, **kwargs): return self def __getattr__(Self, name): return self 

add specfic cases etc. etc.

+6
Jan 10 '10 at 6:05
source share

You can either drop your own layouts, as Anurag Uniyal suggested, or you can use a mocking structure.

In response to those who say that you can just create a regular user just like in Django ... I would suggest that this defeats the unit test point. A unit test should not touch the database, but when you created the user, you changed the database, so we would like to mock it.

+6
Jan 10
source share

You do not need to mock users, because you can just create it in your test - the database will be destroyed after the test is completed.

To mock requests, use this snippet from Simon Willison.

+3
Jan 10 '10 at 10:18
source share



All Articles