尝试使用 py.test 从两个字典断言 return 值时出现 AssertionError

AssertionError when trying to assert return value from two dictionaries with py.test

我正在测试我一直在学习的基于文本的游戏 Python。最近几天我一直在忙于为我不断遇到的问题寻找解决方案。我尝试了多种测试方法,但它们最终都给我同样的错误。

问题是以下断言错误(使用py.test):

 E       AssertionError: assert <Textgame.Waffle.WineFields object at 0x03BDECD0> == 
 <Textgame.Waffle.WineFields object at 0x03BD00D0>

显然对象(Textgame.Waffle.WineFields)是正确的,只是位置不同。我不在乎位置。我认为这是因为我使用的是两个内容相同的单独词典。但是,如果可能的话,我更愿意继续使用这本词典。

测试的最小工作示例如下所示:

import Textgame.Waffle

def test_change_map():

    roomnames = {
        "the wine fields" : Textgame.Waffle.WineFields(),
    }

    room = "the wine fields"
    next_room = roomnames[room]

    assert Textgame.Waffle.Map(room).change(room) == next_room

我要声明的 Textgame.Waffle 游戏如下所示:

class WineFields(object):
    pass

class Map(object):

    roomnames = {
        'the wine fields': WineFields(),
    }

    def __init__(self, next_one):
        self.next_one = next_one

    def change(self, next_one):
        return Map.roomnames[next_one]

我尝试了一些方法来解决这个问题,例如使用

def __eq__(self, other):
    return self.next_one == other.next

在地图 class 中,但要么我放错了,要么我根本不应该使用它来解决这个问题。我从另一个关于大致相同问题的 Whosebug 页面得到了这个想法:

Learn Python the Hard Way, Ex 49 : Comparing objects using assert_equal

有人可以向我解释一下我如何断言我得到的输出是我所期望的,而不用担心位置是否相同吗?

您需要能够识别每个实例:

class X:

    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        return self.x == other.x 

这意味着构建它们需要一个参数:

one = X(1)
other = X(1)
one == other

由于成员 x 相等,两个不同的实例将彼此等同。

事实上,我只是复制了您 reference

问题中已接受的答案