ex47自动化测试

1、这里用到了一个测试工具,nosetests,通过anaconda安装了nose程序包,然后使用了里边的assert_equal命令以及Nose.tool中的工具。

Nose会自动查找源文件、目录或者包中的测试用例,符合正则表达式(?:^|[\b_\.%s-])[Tt]est,以及TestCase的子类都会被识别并执行。
例如:我们可以将python脚本文件名以“_test”结尾或包含“_test_”,方法名以“_test”结尾。
 
关于nose暂时先只了解到这些,更多的后边遇到再理解。
2、测试内容
首先是需要进行测试的对象:
 1 #-*- coding: UTF-8 -*- 
 2 
 3 
 4 class Room(object):
 5     
 6     def __init__(self, name, description):
 7         self.name = name
 8         self.description = description
 9         self.paths = {}
10         
11     #get 函数,返回指定键的值,如果指定键不存在,则返回默认值None
12     def go(self, direction):
13         return self.paths.get(direction, None)
14         
15     def add_paths(self, paths):
16         self.paths.update(paths)

接着是测试骨架:

 1 #-*- coding: UTF-8 -*-
 2 from nose.tools import *
 3 from ex47.game import Room
 4 #测试模块中的__init__函数是否正常运行
 5 def test_room():
 6     gold = Room("GoldRoom",
 7                 """This room has gold in it you can grab.There's a 
 8                 door to the north.""")
 9     assert_equal(gold.name, "GoldRoom")#assert_equal是nose里边的函数,如果前后两个相等,就正常运行。
10     assert_equal(gold.paths,{})
11 #测试paths函数    
12 def test_room_paths():
13     center = Room("Center", "Test room in the center.")
14     north = Room("North", "Test room in the north.")
15     south = Room("South", "Test room in the south.")
16     
17     center.add_paths({'north': north, 'south': south})
18     assert_equal(center.go('north'), north)
19     assert_equal(center.go('south'), south)
20 #测试通过go函数连接整个地图是否能够实现    
21 def test_map():
22     start = Room("Start", "You can go west and down a hole.")
23     west = Room("Trees", "There are trees here, you can go east.")
24     down = Room("Dungeon", "It's dark down here, you can gon up.")
25     
26     start.add_paths({'west': west, 'down': down})
27     west.add_paths({'east':start})
28     down.add_paths({'up': start})
29     
30     
31     
32     assert_equal(start.go('west'), west)
33     assert_equal(start.go('west').go('east'), start)
34     assert_equal(start.go('down').go('up'), start)

这里提一下asseert_equal,如果前后两个相等,则测试正确。

最后一条:别太把测试当做一回事,有时候更好的方法是把代码和测试全部删掉,然后重新设计代码。

posted @ 2017-12-30 21:24  丁头零零  阅读(583)  评论(0编辑  收藏  举报