【问题标题】:how to get request object in django unit testing?如何在 Django 单元测试中获取请求对象?
【发布时间】:2012-05-03 21:35:23
【问题描述】:

我有一个函数

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

现在我想单独为上述函数编写单元测试(不调用视图)。 那么我应该如何在TestCase 中调用上述内容。是否可以创建请求?

【问题讨论】:

    标签: python django django-testing


    【解决方案1】:

    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)
    

    【讨论】:

    • 这个代码实际上已经包含在 Django 1.3 版本中。
    • 如果我没看错,来自工厂的虚假请求不会通过中间件过滤。
    【解决方案2】:

    如果您使用 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.TestCase(from django.test import TestCase, SimpleTestCase, TransactionTestCase),您只需键入self.client即可访问任何测试用例中的客户端实例:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        请看这里:Test Client

        @Secator 的回答是完美的,因为它创建了一个模拟对象,这对于一个非常好的单元测试来说确实是首选。但是根据您的目的,使用 Django 的测试工具可能会更容易。

        【讨论】:

          【解决方案5】:

          你可以使用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

          【讨论】:

            猜你喜欢
            • 2016-03-08
            • 2015-06-01
            • 2014-07-04
            • 2021-10-03
            • 2018-03-02
            • 1970-01-01
            • 1970-01-01
            • 2012-12-17
            • 1970-01-01
            相关资源
            最近更新 更多