You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用nosetests测试Python代码时出现SyntaxError,求助排查问题

解决nosetests中的SyntaxError及其他潜在问题

咱们先从你遇到的第一个SyntaxError说起,错误提示指向第9行的assert_equal,但问题其实出在它的上一行:

1. 缺少闭合括号导致的语法错误

在test_room函数里,你实例化Room对象的代码少了一个闭合的圆括号:

# 错误代码
gold = Room ("GoldRoom", """This room has gold in it you can grab. There's a door to the north."""
# 这里缺了一个 )

Python会认为这一行代码还没结束,所以下一行的assert_equal就会被当成不完整代码的一部分,直接触发SyntaxError。

修正这行代码,补上右括号:

gold = Room("GoldRoom", """This room has gold in it you can grab. There's a door to the north.""")

2. 字典误用列表语法的错误

解决第一个问题后,你还会遇到新的语法错误——在test_room_paths和test_map函数中,你用方括号[]来定义键值对,但这是列表的语法,字典应该用大括号{}:

# 错误代码
center.add_paths(['north': north, 'south': south])
# 正确写法
center.add_paths({'north': north, 'south': south})

同样,test_map里的start.add_paths(['west': west, 'down': down])、west.add_paths(['east': start])、down.add_paths(['up': start])都要把[]改成{}。

3. 断言函数拼写错误

在test_map函数里,你把assert_equal拼成了assert_eqaul(字母顺序错误),这会导致运行时找不到这个函数:

# 错误代码
assert_eqaul(start.go('west'), west)
# 正确写法
assert_equal(start.go('west'), west)

修正后的完整测试代码

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)

运行结果

修正后再执行nosetests,就能得到你预期的输出:

$ nosetests
...
Ran 3 tests in 0.008s
OK

内容的提问来源于stack exchange,提问作者CodeyBanks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:10:47