【有书共读15】Python测试驱动开发 读书笔记 09

关于重构

重构时,修改代码或者测试,但不能同时修改。
重构后最好做一次提交:

$ git status # 会看到tests.py,views.py,settings.py,以及新建的templates文件夹

$ git add . # 还会添加尚未跟踪的templates文件夹

$ git diff --staged # 审查我们想提交的内容

$ git commit -m"Refactor home page view to use a template"
我们需要一个 <h1> 元素:

<html>

<head>

<title>To-Do lists</title>

</head>

<body>

<h1>Your To-Do list</h1>

</body>

</html>

看一下功能测试是否认同这次修改:

selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: {"method":"id","selector":"id_new_item"}' ; Stacktrace: [...]

不错,继续修改:

[...]

<h1>Your To-Do list</h1>

<input id="id_new_item" />

</body> [...]

现在呢?

AssertionError: '' != 'Enter a to-do item'

加上占位文字:

<input id="id_new_item" placeholder="Enter a to-do item" />

得到了下述错误:

selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: {"method":"id","selector":"id_list_table"}' ; Stacktrace: [...]

因此要在页面中加入表格。目前表格是空的:

<input id="id_new_item" placeholder="Enter a to-do item" />

<table id="id_list_table">

</table>

</body>

现在功能测试的结果如何?

File "functional_tests.py", line 42, in test_can_start_a_list_and_retrieve_it_later

any(row.text == '1: Buy peacock feathers' for row in rows)

AssertionError: False is not true

有点儿晦涩。可以使用行号找出问题所在,原来是前面我沾沾自喜的那个 any 函数导致的,或者更准确地说是 assertTrue,因为没有提供给它明确的失败消息。可以把自定义的错误消息传给 unittest 中的大多数 assertX 方法:

self.assertTrue(

any(row.text == '1: Buy peacock feathers' for row in rows), "New to-do item did not appear in table"

)

再次运行功能测试,应该会看到我们编写的消息:

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"

多亏这次重构,视图能渲染模板了,也不再测试常量了,现在准备好处理用户的输入了。









#Python##笔记##读书笔记##测试#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务