如何在Django功能测试中触发空值验证?

时间:2019-01-16 00:09:27

标签: python django tdd

我是Django的新手,现在我正在阅读《使用Python的测试驱动开发》一书进行学习。 但是,当我要测试空值验证时,单元测试可以,但是功能测试失败。

我现在正在使用Django 2.1,Python3。我已尽力检查问题的原因,但仍未能通过功能测试

models.py

...
class Item(models.Model):
    text = models.TextField(default='')
    list = models.ForeignKey(List, default=None, on_delete=models.CASCADE)

views.py

...
def new_list(request):
    list_ = List.objects.create()
    item = Item.objects.create(text=request.POST['item_text'],list=list_)
    try:
        item.full_clean()
        item.save()
    except ValidationError:
        list_.delete()
        error = "You can't have an empty list item"
        return render(request, 'home.html', {"error": error})

    return redirect(list_)

test_views.py(成功进行单元测试)

...
def test_validation_errors_are_sent_back_to_home_page_template(self):
    response = self.client.post('/lists/new', data={'item_text':''})
    self.assertEqual(response.status_code, 200)
    self.assertTemplateUsed(response, 'home.html')
    expected_error = escape("You can't have an empty list item")
    self.assertContains(response, expected_error)

test_list_item_validation.py(功能测试失败)

...
def test_cannot_add_empty_list_items(self):
    self.browser.get(self.live_server_url)
    self.browser.find_element_by_id('id_new_item').send_keys(Keys.ENTER)
    error = self.browser.find_element_by_css_selector('.has-error')
    self.assertEqual(error.text, "You can't have an empty list item")

base.html(所有html文件都从此扩展)

...
{% if error %}
    <div class="form-group has-error">
        <span class="help-block">{{ error }}</span>
    </div>
{% endif %}

我希望单元测试和功能测试都正确,但是实际结果是通过了单元测试,但是功能测试失败了

1 个答案:

答案 0 :(得分:1)

好书。自己读。我相信这是您缺少的部分:

def test_cannot_add_empty_list_items(self):
    # Edith goes to the home page and accidentally tries to submit
    # an empty list item. She hits Enter on the empty input box
    self.browser.get(self.live_server_url)
    self.get_item_input_box().send_keys(Keys.ENTER)

    '''
    If you keep reading a little farther, it should tell you that modern browsers
    will not submit forms when fields that are 'required' left are blank.
    '''
    # The browser intercepts the request, and does not load the
    # list page
    self.wait_for(lambda: self.browser.find_elements_by_css_selector(
        '#id_text:invalid'  
    ))

如果您继续阅读一些内容,它应该告诉您,当forms的字段留空时,“现代浏览器不会提交required。它应该给您上面的代码修改。