問題描述
我有與請求對象或用戶對象交互的 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)
如果您要使用 django python shell 或在單元測試中進行測試,您會在其中傳遞什么?這里只需一個 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.
對于外殼或單元測試:
- 如何模擬用戶?
- 如何模擬請求?
推薦答案
對于請求,我會使用 RequestFactory 包含在 Django 中.
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'})
對于用戶,我會按照@ozan 的建議使用 django.contrib.auth.models.User 并且可能使用 factory boy 提高速度(使用 factory boy 你可以選擇不保存到 DB)
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 中模擬用戶和請求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!