习题47 自动化测试

在ex47项目中,从上一习题的项目骨架开始,进行重命名并清理*.pyc文件。遇到导入ex47.game失败的问题,需要排查原因。此外,了解doctest模块用于验证代码片段的交互式会话。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个测试将建立在上个习题的项目骨架基础上。

首先创建一个叫做 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值