编辑《functional_tests.py》
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
# 给出webdriver的路径
drive_path = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver\chromedriver.exe'
# 这是为了忽略浏览器提示“正受到自动化软件的控制”
option = webdriver.ChromeOptions()
option.add_argument('disable-infobars')
self.browser = webdriver.Chrome(executable_path=drive_path, chrome_options=option)
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_can_start_a_list_and_retrieve_it_later(self):
self.browser.get('http://localhost:8000')
self.assertIn('To-Do', self.browser.title)
header_text = self.browser.find_element_by_tag_name('h1').text
self.assertIn('To-Do',header_text)
#应用邀请他输入一个代办事项
inputbox = self.browser.find_element_by_id('id_new_item')
self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item')
inputbox.send_keys(Keys.ENTER)
table = self.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
self.assertTrue(
any(row.text == '1: Buy peacock feathers' for row in rows),"New to-do item did not appear in table"
)
self.fail('finish the test!')
if __name__ == '__main__':
unittest.main(warnings='ignore')
使用模板重构HTML,新建文件夹lists/templates/home.html。在home.html中写入:
<html>
<head>
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do lists</h1>
<input id="id_new_item" placeholder="Enter a to-do item"/>
<table id="id_list_table">
<tr></tr>
</table>
</body>
</html>
为了能找到homl.html文件,需要在settings.py文件的INSTALLED_APPS中添加‘lists’。
单元测试:为了测试django渲染了正确的模板,在《tests.py》中写入:
from django.test import TestCase
from django.core.urlresolvers import resolve
from .views import home_page
from django.http import HttpRequest
from django.template.loader import render_to_string
# Create your tests here.
class HomePageTest(TestCase):
def test_root_url_resolve_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
self.assertTrue(response.content.startswith(b'<html>'))
self.assertIn(b'<title>To-Do lists</title>',response.content)
self.assertTrue(response.content.endswith(b'</html>'))
expected_html = render_to_string('home.html')
self.assertEqual(response.content.decode(), expected_html)
重点注意:rows = table.find_elements_by_tag_name('tr')
中elements有个s,写漏了会报不能迭代的错误