Django测试request.method ==' POST'不工作

时间:2016-11-22 20:13:44

标签: python django

我正在使用python编写TDD示例,并尝试接受发布请求。

Django的<audio controls> <source src="https://s3-sa-east-1.amazonaws.com/ell-random-sharing/st_293_1.ogg" type="audio/ogg"> Your browser does not support the audio element. </audio> <audio controls> <source src="https://s3-sa-east-1.amazonaws.com/ell-random-sharing/st_294_1.ogg" type="audio/ogg"> Your browser does not support the audio element. </audio> HttpRequest.method页面建议使用以下代码段以不同的方式响应GET和POST

if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()

考虑到这一点,我的观点设置如下:

from django.shortcuts import render
from django.http import HttpResponse
from items.models import Item

def index_page(request):

    name = ''
    if request.method == 'POST':
        name = request.POST['item']
        Item.objects.create(name=name)

    return render(request, 'items/index.html', {'item': name})

我的测试文件包含以下内容

from django.test import TestCase
from django.http import HttpRequest
from items.views import index_page
from items.models import Item

class IndexPageTest(TestCase):

    def test_index_page_can_save_a_post_request(self):
        request = HttpRequest()
        request.POST['item'] = 'MyItem'
        response = index_page(request)

        self.assertEqual(Item.objects.count(), 1)
        self.assertEqual(Item.objects.first().name, 'MyItem')

产生以下错误

======================================================================
FAIL: test_index_page_can_save_a_post_request (items.tests.IndexPageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/items/tests.py", line 43, in test_index_page_can_save_a_post_request
    self.assertEqual(Item.objects.count(), 1)
AssertionError: 0 != 1

然而,当我将视图改为以下时,测试通过。

from django.shortcuts import render
from django.http import HttpResponse
from items.models import Item

def index_page(request):

    name = request.POST.get('item', '')
    if name:
        Item.objects.create(name=name)

    return render(request, 'items/index.html', {'item': name})

显然,我的页面正在重新发布POST请求,测试正在发送POST数据,但我不确定为什么if request.method == 'POST':行似乎不起作用。

$ python --version
Python 3.5.2 :: Continuum Analytics, Inc.
$ django-admin --version
1.10.3

1 个答案:

答案 0 :(得分:1)

您的测试不是发送帖子。您应该使用RequestFactory而不是直接实例化HttpRequest。甚至更好,使用内置的测试客户端。