如何在django中模拟用户和请求 [英] How to mock users and requests in django

查看:153
本文介绍了如何在django中模拟用户和请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有django代码与请求对象或用户对象进行交互。例如:

  foo_model_instance = models.get_or_create_foo_from_user(request.user)

如果要使用django python shell或单元测试进行测试,那么你会在那里通过什么?这里只需一个User对象即可,但需要一个模拟请求对象也会经常出现。



对于shell或单元测试:




  • 你如何模拟用户?

  • 你如何模拟请求?


解决方案

对于请求,我将使用 RequestFactory

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

对于用户,我将使用django.contrib.auth.models.User作为@ozan建议也许与工厂男孩的速度(与工厂的男孩,你可以选择不保存到DB)


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?

解决方案

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)

这篇关于如何在django中模拟用户和请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆