如何在django单元测试中获取请求对象?

问题描述:

我具有作为如何在django单元测试中获取请求对象?

def getEvents(eid, request): 
    ...... 

现在我想要写用于分别在上述功能单元测试(而不调用视图)。 那么我应该如何在TestCase上面调用上述内容。是否有可能创建请求?

this solution

from django.utils import unittest 
from django.test.client import RequestFactory 

class SimpleTest(unittest.TestCase): 
    def setUp(self): 
     # Every test needs access to the request factory. 
     self.factory = RequestFactory() 

    def test_details(self): 
     # Create an instance of a GET request. 
     request = self.factory.get('/customer/details') 

     # Test my_view() as if it were deployed at /customer/details 
     response = my_view(request) 
     self.assertEqual(response.status_code, 200) 
+4

该代码实际上已经从1.3版本包含在Django。请参阅此处的[文档](https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.client.RequestFactory)。 – 2012-04-23 09:28:58

+1

如果我正确地看到此错误,那么来自工厂的假请求不会通过中间件进行过滤。 – 2014-09-08 10:01:52

+3

更新文档[链接](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/#example) – dragonx 2016-05-06 05:49:34

你的意思是def getEvents(request, eid)吧?

使用Django unittest,您可以使用from django.test.client import Client来提出请求。

在这里看到:Test Client

@ Secator的答案是知府,因为它创造这实在是首选一个很好的单元测试模仿对象。但根据你的目的,使用Django的测试工具可能更容易。

使用RequestFactory创建一个虚拟请求。

+1

感谢您链接到doc – 2015-10-08 15:07:07

如果使用django的测试客户端(from django.test.client import Client),可以像这样从响应对象访问请求:

from django.test.client import Client 

client = Client() 
response = client.get(some_url) 
request = response.wsgi_request 

,或者如果使用的是django.TestCasefrom django.test import TestCase, SimpleTestCase, TransactionTestCase)可以在任意的测试用例仅通过访问客户端实例键入self.client

response = self.client.get(some_url) 
request = response.wsgi_request 

您可以使用Django测试客户端

from django.test import Client 
c = Client() 
response = c.post('/login/', {'username': 'john', 'password': 'smith'}) 
response.status_code 
response = c.get('/customer/details/') 
response.content 

更多细节
https://docs.djangoproject.com/en/1.11/topics/testing/tools/#overview-and-a-quick-example