Learn Python The Hard Way学习(47) - 自动化测试


不断的输入命令去测试你游戏是很乏味的,为什么我们不写一些测试代码去测试程序呢?当你改变你的程序时,只要运行一下测试代码就能确保你的修改是否正确。当然,自动化测试不能测试出所有的错误,不过也可以为我们节约很多时间。

你要开始为你的代码写自动化测试程序了,这将会让你成为更好的程序员。

我不会尝试解释为什么你要写测试代码。我只是说,你要成为程序员,而编程是无聊而乏味的工作,测试软件也是无聊和乏味的,所以你要写一些自动化的测试代码去完成测试工作。

写测试代码能让你的大脑更加强壮,写测试代码能让你更加理解你写的代码的功能和原理,对细节的了解也会增加。

编写一个测试用例
我们来写一个简单的测试的例子,这个例子是基于项目骨架的新项目。

首先,从项目骨架创建一个ex47项目。确保重命名了NAME。

然后,创建一个文件ex47/game.py。代码如下:
[python]
class Room(object): 
 
 
    def __init__(self, name, description): 
        self.name = name 
        self.description = description 
        self.paths = {} 
 
 
    def go(self, direction): 
        return self.paths.get(direction, None) 
 
 
    def add_paths(self, paths): 
        self.paths.update(paths) 


修改测试文件为:
[python] 
from nose.tools import * 
from ex47.game import Room 
 
 
 
 
def test_room(): 
    gold = Room("GoldRoom",  
                """This room has gold in it you can grab. There's a
                door to the north.""") 
    assert_equal(gold.name, "GoldRoom") 
    assert_equal(gold.paths, {}) 
 
 
def test_room_paths(): 
    center = Room("Center", "Test room in the center.") 
    north = Room("North", "Test room in the north.") 
    south = Room("South", "Test room in the south.") 
 
 
    center.add_paths({'north': north, 'south': south}) 
    assert_equal(center.go('north'), north) 
    assert_equal(center.go('south'), south) 
     
def test_map(): 
    start = Room("Start", "You can go west and down a hole.") 
    west = Room("Trees", "There are trees here, you can go east.") 
    down = Room("Dungeon", "It's dark down here, you can go up.") 
 
 
    start.add_paths({'west': west, 'down': down}) 
    west.add_paths({'east': start}) 
    down.add_paths({'up': start}) 
 
 
    assert_equal(start.go('west'), west) 
    assert_equal(start.go('west').go('east'), start) 
    assert_equal(start.go('down').go('up'), start) 


这个文件从ex47.game模块中导入Room类,以便你可以测试它。测试函数以test_开始,这里测试了创建房间,保存房间。 www.2cto.com

最重要的函数是assert_equal,它能够比较你给出的变量,如果你的函数返回错误的结果,nosetests就会打印错误信息。

测试规则
把测试代码放到tests文件夹下,命名是BLAH_tests.py。不然nosetests不能运行它们。
为每一个模块写一个测试文件。
保持测试用例简洁,如果不简洁也不用担心,一般测试用例都比较乱。
经过测试用例会比较乱,但是还是要尽量保持简洁,删除重复的代码,最好写一个函数来解决代码重复问题,就这样做吧,以后你会感激我的。
最后,不要太依赖测试。有时候,最好的办法是重新设计。
运行结果
root@he-desktop:~/python/projects/ex47# nosetests
...
----------------------------------------------------------------------
Ran 3 tests in 0.019s

OK
试着弄点错误进去,看看会给出什么提示 。

加分习题
1. 学习关于nosetests的知识,或者学习其他可选择的测试方法。
2. 学习doc tests,看看你是否喜欢这种测试方式。
3. 改进Room类,这次要边写代码,边写测试用例。
作者:lixiang0522

相关内容

    暂无相关文章

评论关闭