最近在看一本书《Test-Driven Development with Python》,里面非常详细的介绍了如何一步一步通过测试驱动开发(TDD)的方式开发Web项目。刚好这本书中使用了我之前所了解的一些技术,Django、selenium、unittest等。所以,读下来受益匪浅。
我相信不少开发都写单元测试,不过,一般是先写功能代码,然后,再写单元测试用例,在编写单元测试用例的过程中,可能需要调整功能代码,从而使单元测试用例通过。但是TDD就特别要求先写测试用例,后写实现代码。这一开始确实有些难。
这里就选择一个简单的例子向各位介绍一下TDD的流程(套路)。
编写功能测试用例:
首先,编写功能测试用例,functional_tests.py
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://127.0.0.1:8000")
assert "Django" in browser.title
你没看错,这就是由Selenium编写的功能测试代码。打开Firefox浏览器,并访问http://127.0.0.1:8000,通过assert 判断浏览器标题是否包含“Django”。
然后,运行该测试用例。
D:\pydj>python functional_tests.py
Traceback (most recent call last):
File "functional_tests.py", line 6, in <module>
assert "Django" in browser.title
AssertionError
测试用例失败了,这是必然的,因为我们还没有创建被测试的项目。但,这同样也是我们想要的结果。TDD的套路就是通过编写功能代码,使测试用例通过。
创建项目:
接下来创建Django项目:
D:\pydj>django-admin startproject superlists
当前项目结构如下:
├─ functional_tests.py
└─ superlists
├─ manage.py
└─ superlists
├─ __init__.py
├─ settings.py
├─ urls.py
└─ wsgi.py
进入项目目录,启动项目:
D:\pydj> cd superlists D:\pydj\superlists>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. June 13, 2016 - 23:23:29 Django version 1.9.7, using settings 'superlists.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. |
再次运行功能测试用例,functional_tests.py
接下来继续编写功能测试用例。functional_tests.py
#coding=utf-8 from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.close() def test_case_start_a_list_and_retrieve_it_later(self): # 小明听说有一个很酷的在线代办事项应用 # 她去看了这个应用首页 self.browser.get("http://127.0.0.1:8000") # 它注意到网页的标题和头部包含“To-Do”这个词语。 self.assertIn("To-Do", self.browser.title) if __name__ == '__main__': unittest.main() |
这里用到了unittest 单元测试框架。如果,你不懂Python的单元测试,建议读者去学习unittest。
执行测试用例:
C:\Python35\python.exe D:/pydj/functional_tests.py F ====================================================================== FAIL: test_case_start_a_list_and_retrieve_it_later (__main__.NewVisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:/pydj/functional_tests.py", line 21, in test_case_start_a_list_and_retrieve_it_later self.assertIn("To-Do", self.browser.title) AssertionError: 'To-Do' not found in 'Welcome to Django' ---------------------------------------------------------------------- Ran 1 test in 3.491s FAILED (failures=1) |