《笨方法学Python》习题47

练习 47: 自动化测试

  1. 项目骨架中新建一个叫做ex47的项目,创建一个简单的ex47/game.py,里面放一些用来被测试的代码。我们放一个小class进去,作为我们的测试对象:
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)
  1. 新建tests/ex47_tests.py,把测试骨架改成这个样子:
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)

测试结果:

~/projects/simplegame$ nosetests
...
----------------------------------------------------------------------
Ran 3 tests in 0.005s

OK

注:
其中Assert.assertEquals()使用方法:把一个预期结果作为1参传递进去. 2参传递我们需要测试的方法. 然后执行. 相等, 代码继续往下执行, 不相等, 中断执行, 抛出异常信息!!!

加分习题

  1. 仔细读读 nosetest 相关的文档,再去了解一下其他的替代方案。
  2. 了解一下 Python 的 “doc tests” ,看看你是不是更喜欢这种测试方式。
  3. 改进你游戏里的 Room,然后用它重建你的游戏,这次重写,你需要一边写代码,
    一边把单元测试写出来。

你可能感兴趣的:(《笨方法学Python》习题47)