使用unittest测试Django是否正常启动

unsplash

TDD在编写测试用例之前,似乎还要先准备文档(注释)

讲故事

在测试中,也要讲好故事。一个好的故事,涵盖了一个使用场景。在测试中利用注释可以很好的讲故事。

修改 测试Django的启动functional_tests.py 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from selenium import webdriver

browser = webdriver.Firefox()

# Edith has heard about a cool new online to-do app. She goes
# to check out its homepage
browser.get('http://localhost:8000')

# She notices the page title and header mention to-do lists
assert 'To-Do' in browser.title

# She is invited to enter a to-do item straight away

# She types "Buy peacock feathers" into a text box (Edith's hobby
# is tying fly-fishing lures)

# When she hits enter, the page updates, and now the page lists
# "1: Buy peacock feathers" as an item in a to-do list

# There is still a text box inviting her to add another item. She
# enters "Use peacock feathers to make a fly" (Edith is very methodical)

# The page updates again, and now shows both items on her list

# Edith wonders whether the site will remember her list. Then she sees
# that the site has generated a unique URL for her -- there is some
# explanatory text to that effect.

# She visits that URL - her to-do list is still there.

# Satisfied, she goes back to sleep

browser.quit()

通过注释,讲好了如何使用的故事。

Unittest 模块

继续修改 functional_tests.py, 这次使用 unittest 来写测试用例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from selenium import webdriver
import unittest

class NewVisitorTest(unittest.TestCase):

def setUp(self):
self.browser = webdriver.Firefox()

def tearDown(self):
self.browser.quit()

def test_can_start_a_list_and_retrieve_it_later(self):
# Edith has heard about a cool new online to-do app. She goes
# to check out its homepage
self.browser.get('http://localhost:8000')

# She notices the page title and header mention to-do lists
self.assertIn('To-Do', self.browser.title)

# She is invited to enter a to-do item straight away
[...rest of comments as before]

if __name__ == '__main__':
unittest.main(warnings='ignore')

然后在运行该文件进行测试。

参考资料

0%