2013-10-22 62 views
1

我測試我的項目,我需要測試Django的形式,但我不知道該怎麼做,這裏的代碼的Django/Python測試Django的形式

if request.method == 'POST': # If the form has been submitted... 
    name_add = request.POST.get("name") 
    form = AddForm(request.POST) # A form bound to the POST datas 
    not_add = 0 
    if form.is_valid(): # All validation rules pass 
     for n in Product.objects.filter(dashboard = curr_dashboard): 
      if n.name == name_add: 
       not_add = 1 
     if not_add != 1: 
      obj = form.save(commit=False) 
      obj.dashboard = curr_dashboard 
      obj.save() 
      curr_buylist.add_product(obj.id) 
      return HttpResponseRedirect(request.get_full_path()) # Redirect after POST 
     else: 
      forms.ValidationError("You already have this") 
      return HttpResponseRedirect(request.get_full_path()) 

我在這裏證明它,添加到數據庫。但是,我如何測試它?這裏是我寫的測試

def test_index_form(self): 
    request = self.factory.post('main/index') 
    request.user = User.objects.get(username= 'admin') 
    response = index(request) 

    self.assertEqual(response.status_code, 200) 

回答

1

我覺得你的測試是一個好的開始。不幸的是,它只是測試表單無效的情況。除了測試狀態代碼之外,我還會測試是否正在加載正確的模板,也許還要測試未綁定的表單是否在上下文中(基本上按照預期測試視圖中正確的條件執行):

self.assertTemplateUsed(response, 'your_template.html') 
self.assertIsInstance(response.context['form'], AddForm) 

在您的測試中提供有效的表單數據並確保創建一個新對象也是一個想法,如預期的那樣。

將無效數據發佈到您的視圖並檢查是否發出重定向也可能是個好主意