接着修改首页
运行 $ python functional_tests.py
,我们的功能测试依然是失败的,所以需要继续修改代码,直至测试通过
现在我们的HTML是单独保存在模板里,所以可以放心的修改。我们根据测试报错修改list/templates/home.html
<html>
<head>
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
</body>
</html>
添加完成后,我们在去superlist目录,运行功能测试 $ python functional_tests.py
,报错找不到元素<h1>
运行结果:报错未缺少元素[id="id_new_item"]
再去查看代码,发现functional_tests.py
里测试代码里有这一项的测试,用的是selenium方法寻找元素
应用邀请她输入一个待办事项
inputbox = self.brower.find_element_by_id('id_new_item')
我们的home.HTML里是没有的,所以我们继续修改list/templates/home.html
,添加<input id="id_new_item"/>
元素
<html>
<head>
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<input id="id_new_item"/>
</body>
</html>
添加完后,运行$ python functional_tests.py
,断言报错:AssertionError: '' != 'Enter a to-do item'
assertEqual()方法是判断相等,我们打开functional_tests.py
self.assertEqual(
inputbox.get_attribute('placeholder'),
'Enter a to-do item'
)
继续修改home.HTML,添加body内容
…
<input id="id_new_item" placeholder = "Enter a to-do item"/>
…
运行$ python functional_tests.py
,报错: Message: Unable to locate element: [id="id_list_table"]
缺少id_list_table表单,我们继续修改home.HTML,添加
<html>
<head>
<title>To-Do lists</title>
</head>
<>
<h1>Your To-Do list</h1>
<input id="id_new_item" placeholder = "Enter a to-do item"/>
<table id="id_list_table">
</table>
</body>
</html>
运行$ python functional_tests.py
,报错: Message: Unable to locate element: tr
**注意:**作者的home.html内容没有,但是测试Case里是有的检查元素
rows = table.find_element_by_tag_name('tr') # 1
这一行,作者是没有的,所以我们本地加上
<html>
<head>
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<input id="id_new_item" placeholder = "Enter a to-do item"/>
<table id="id_list_table">
<tr>
</tr>
</table>
</body>
</html>
添加标签后,继续运行$ python functional_tests.py
,报错:TypeError: 'FirefoxWebElement' object is not iterable
打开并编辑superlists/functional_tests.py
rows = table.find_element_by_tag_name('tr')
改为
rows = table.find_elements_by_tag_name('tr')
如果元素寻找单个元素时
find_element_by_tag_name
如果有多个元素时,需要用
find_elements_by_tag_name
继续运行$ python functional_tests.py
,报错:AssertionError: False is not true
any函数这里有问题
any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
元素除了是 0、空、FALSE 外都算 TRUE。
给any函数带上参数,"New to-do item did not appear in table"
即可
self.assertTrue(
any(row.text == '1: Buy peacock feathers' for row in rows),
"New to-do item did not appear in table"
)
继续运行python functional_tests.py
,运行报错:AssertionError: False is not true : New to-do item did not appear in table
这个问题下次解决,我们先提交代码
$ git diff
$ git commit -am "Front page HTML now generated from a template"
TDD流程总结:
至此,我们已经时间了TDD流程中涉及的所有概念
· 功能测试
· 单元测试
· 重复进行“单元测试/编写代码”
· 重构
我们可以将这个过程画个流程图
首先我们编写一个测试Case,运行Case并看着它会失败。然后编写最少量的代码取得一些进展,再次运行测试,如次不断重复,直到测试通过为止,或许最后还需要重构代码,测试能保证不破坏任何功能
既有功能测试,又有单元测试,该怎么运用这个流程呢?你可以把功能测试当作循环的一种高层视角,而“编写代码让功能测试通过”这一步则是另一个小型TDD 循环,这个小循环使用单元测试
编写一个功能测试,如果功能测试。
“编写代码让功能测试通过”这一步是一个小型TDD 循环:编写一个或多个单元测试,然后进入“单元测试/ 编写代码”循环,直到单元测试通过为止。然后回到功能测试,查看是否有进展。这一步还可以多编写一些应用代码,再编写更多的单元测试,如此一直循环下去。