这个测试将建立在上个习题的项目骨架基础上。
首先创建一个叫做 ex47 的项目,要做这些事情:
1.复制骨架到 ex47 中。
2.将带有 NAME 的东西都重命名为 ex47。
3.文件中的 NAME 全部改成 ex47。
4.删除所有*.pyc 文件,确保已经清理干净。
挺简单的。然后放一个测试对象进去:
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)
准备好了这个文件,然后把单元测试骨架改成下面这样:
from nose.tools import *
from ex47.game import Room
def test_room():
gold = Room("GoldRoom",
"""This room has gold in ti 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 hte 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 is 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)
本意是要这么测试,书上要求直接 nosetests 就行了,运行也是 OK
但是我试了试 python ex47_tests.py 这个命令,提示说 ex47.game 无法导入,找不到这个东西。不知道为什么?
==================================================================================================
附加练习
2. 网上这么说的: doctest 模块会搜索那些看起来像交互式会话的 Python 代码片段,然后尝试执行并验证结果
https://my.oschina.net/lionets/blog/268542