簡體   English   中英

Django Test request.method =='POST'不起作用

[英]Django Test request.method == 'POST' not working

我正在使用TDD開發python中的示例,並嘗試接受發布請求。

Django的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

您的測試發送帖子。 您應該使用RequestFactory而不是直接實例化HttpRequest。 甚至更好,請使用內置的測試客戶端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM