是否可以通过django测试客户端中的post请求传递request.body?

时间:2015-08-27 20:09:19

标签: python django unit-testing django-testing

到目前为止我还没有找到任何办法。

https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.Client.options 

显示选项允许request.body通过get请求但无法找到通过post请求传递的任何方法。任何想法,我一直在寻找几个小时。

3 个答案:

答案 0 :(得分:3)

是:

self.client.generic('POST', '/url', 'raw post data')

答案 1 :(得分:1)

如果你真的想这样做:

request.body = b'{"first": "fred", "last": "dredd"}'

你应该这样做:

request._body = b'{"first": "fred", "last": "dredd"}'

答案 2 :(得分:-1)

POST的正文作为字典作为TestClient.post的第二个参数发送:

class MyTestCase(TestCase):

    def my_test_function(self):
        response = self.client.post('/my-post-handler/', {'first': 'fred', 'last': 'dredd'})

        self.assertEqual(response.status_code, 200)

如果这对您的用例不起作用,您可能希望一起跳过TestClient并直接测试视图函数。为此,您需要使用RequestFactory,并将其作为请求参数发送到视图。像这样的东西,大量借鉴我链接到的文档:

from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase

from .views import my_view

class SimpleTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_details(self):
        request = self.factory.get('/customer/details')

        # Recall that middleware are not supported. You can simulate a
        # logged-in user by setting request.user manually.
        request.user = self.user

        # Set the body to whatever you need it to be
        request.body = b'{"first": "fred", "last": "dredd"}'

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