[英]Django Test request.method == 'POST' not working
I am working on an example in TDD with python and am trying to accept a post request. 我正在使用TDD开发python中的示例,并尝试接受发布请求。
Django's Request and response objects page for HttpRequest.method
suggests using the following snippet to responde to GET and POST differently Django的
HttpRequest.method
的请求和响应对象页面建议使用以下代码段以不同方式响应GET和POST
if request.method == 'GET':
do_something()
elif request.method == 'POST':
do_something_else()
With this in mind, my view is setup like so: 考虑到这一点,我的视图设置如下:
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})
My test file contains the following 我的测试文件包含以下内容
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')
Which yields the following error 产生以下错误
======================================================================
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
However when I alter the view to the following, the test passes. 但是,当我将视图更改为以下内容时,测试通过。
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})
Clearly, my page is repsonding to POST requests and the test is sending POST data, but I'm not sure why the if request.method == 'POST':
line does not appear to work. 显然,我的页面响应POST请求,并且测试正在发送POST数据,但是我不确定为什么
if request.method == 'POST':
行似乎不起作用。
$ python --version
Python 3.5.2 :: Continuum Analytics, Inc.
$ django-admin --version
1.10.3
Your test isn't sending a post. 您的测试未发送帖子。 You should use the RequestFactory rather than instantiating HttpRequest directly.
您应该使用RequestFactory而不是直接实例化HttpRequest。 Or even better, use the built in test client.
甚至更好,请使用内置的测试客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.