1、自动化测试的目的函数
利用自动化的测试代码取代手动测试,使得程序中的一些初级bug能够被自动检出,而无需人工进行重复繁琐的测试工做。单元测试
2、编写测试用例测试
利用上一节编写的skeleton,此次在projects中建立一个ex47文件夹,将骨架文件复制到ex47下,而后执行如下操做:spa
1. 将全部带NAME的东西所有重命名为ex47命令行
2. 将所用文件中的NAME所有改成ex47code
3. 删除全部的.pyc文件,确保清理干净(该类文件为编译结果?)对象
注意,书中提示能够经过执行nosetests命令来运行测试,但此步须要cd到tests的上级目录,而后直接在命令行键入nosetests运行。blog
下面在bin同级的ex47文件夹下建立一个game.py,并写一些类做为测试对象,如ip
1 class Room(object): 2 3 def __init__(self, name, description): 4 self.name = name 5 self.description = description 6 self.paths = {} 7 8 def go(self, direction): 9 return self.paths.get(direction, None) #dict.get(key, default=None) 查找键,指定键不存在时,返回default值 10 11 def add_paths(self, paths): 12 self.paths.update(paths) #dict.update(dict2) 将dict2里的键值对更新到dict里
下面将单元测试骨架修改为下面的样子:get
1 from nose.tools import * 2 from ex47.game import Room 3 4 def test_room(): 5 gold = Room('GoldRoom', 6 """This room has gold in it you can grab. There's a 7 door to it in the north.""") 8 assert_equal(gold.name, "GoldRoom") 9 assert_equal(gold.paths, {}) 10 11 def test_room_paths(): 12 center = Room('Center', "Test room in the center.") 13 north = Room('North', "Test room in the north.") 14 south = Room('South', "Test room in the south.") 15 16 center.add_paths({'north':north, 'south':south}) 17 assert_equal(center.go('north'), north) 18 assert_equal(center.go('south'), south)
还能够根据模块的功能增长更多的测试用例(上面以test开头的函数,称为test case),用assert_equal断言来判断实际输出值和理想输出值是否一致。
3、测试指南
1. 测试文件要放在tests/目录下,而且命名为name_tests.py,不然nosetests就没法识别。这样也能够防止测试代码和别的代码相互混淆。
2. 为建立的每个模块写一个测试文件。
3. 测试用例保持简短。
4. 保持测试用例的整洁,用辅助函数代替重复代码。
4、其余建议
了解doc tests,这是一种另外的测试方式。(nose项目彷佛已经再也不更新?)