2015-08-13 23 views
0

我正在Django中創建一個應用程序,我有一個視圖,它接收來自html代碼的表單,並在數據庫中搜索模型中是否存在表單中指定值的任何模型實例。我如何在Django中測試具有表單的視圖?

問題是,我是新的Django,我真的不知道如何測試視圖的功能(即:如果視圖的響應有一個值的列表導致搜索窗體的值在請求中)。

在這裏,我把我的觀點的示例代碼:

@login_required 
def view(request): 

# If it's a HTTP POST, we're interested in processing form data. 
if request.method == 'POST': 

    form = Form(data=request.POST) 

    # If the form is valid 
    if (form.is_valid()): 

     resulting_of_search = ModelA.objects.filter(Q(att1=request.POST[attr1]) & ...) 



    else: 
     resulting_of_search = [] 


# Not a HTTP POST, so we render our form using two ModelForm instances. 
# These forms will be blank, ready for user input. 
else: 
    form = Form() 
    resulting_of_search= [] 



# Render the template depending on the context. 
return render(request, 
     'url/url.html', 
     {'resulting':resulting_of_search}) 

回答

0

您是否嘗試過Django Testing Tutorial?從本質上講,你只需要發送一篇文章到你的視圖,並測試響應返回你所期望的。

例如..

def test_index_view_with_no_questions(self): 
    """ 
    If no questions exist, an appropriate message should be displayed. 
    """ 
    response = self.client.get(reverse('polls:index')) 
    self.assertEqual(response.status_code, 200) 
    self.assertContains(response, "No polls are available.") 
    self.assertQuerysetEqual(response.context['latest_question_list'], []) 

從文檔兩者。你會想改變最後一行,以便聲明'結果'在上下文中。或者檢查它是否包含您正在查找的結果的特定列表。這樣的..

def test_results(self): 
    response = self.client.get(reverse('ensaioak_bilatu')) 
    self.assertQuerySetEqual(response.context['resulting'], [...whatever you expect resulting to contain...]) 
+0

我做了,但我的問題是:如果我有一個「返回呈現」在視圖的結尾如何測試視圖的結果? – jartymcfly

+0

我將編輯我的答案以添加示例。 – Alistair

+0

什麼意思是「reverse('polls:index')」sentence? – jartymcfly