python - 艰难地学习 Python,Ex 49 : Comparing objects using assert_equal

标签 python unit-testing

是否可以使用 assert_equal 来比较对象?我一直看到这个错误:

AssertionError: <ex49.parser.Sentence object at 0x01F1BAF0> !=
<ex49.parser.Sentence object at 0x01F1BB10>

相关代码片段:

def test_parse_subject():

    testsentence = "princess go east"
    result = lexicon.scan(testsentence)
    Sent = parse_sentence(result)
    ResultSent = Sentence(('subject', 'princess'),
                      ('verb', 'go'),
                      ('object', 'east'))
    print ResultSent.subject
    print ResultSent.verb
    print ResultSent.object
    print Sent.subject
    print Sent.verb
    print Sent.object
    assert_equal(Sent, ResultSent)

屏幕上的打印输出表明对象具有相同的内容 - 但出现断言错误。为什么是这样?有什么方法可以使用 assert_equal 来覆盖它吗?

最佳答案

我相信您需要在 Sentence 类上实现 __eq__ 方法。

assertEqual(first, second, msg=None)¶ Test that first and second are equal. If the values do not compare equal, the test will fail.

In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or unicode or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message (see also the list of type-specific methods).

Python unittest documentation

The correspondence between operator symbols and method names is as follows: xlt(y), x<=y calls x.le(y), x==y calls x.eq(y), x!=y and x<>y call x.ne(y), x>y calls x.gt(y), and x>=y calls x.ge(y).

Python data model documentation

一个例子:

import unittest


class A:

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

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


class Test(unittest.TestCase):

    def test(self):
        a1 = A(1)
        a12 = A(1)
        a2 = A(2)

        self.assertEqual(a1, a1, 'a1 != a1')
        self.assertEqual(a1, a12, 'a1 != a12')
        self.assertEqual(a1, a2, 'a1 != a2')

def main():
    unittest.TestRunner(Test())

if __name__ == '__main__':
    unittest.main()

现在评论 __eq__ 方法并查看差异。

关于python - 艰难地学习 Python,Ex 49 : Comparing objects using assert_equal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9306242/

相关文章:

python - 如何编写 JIT 库?

python - 类型错误 : init() missing 1 required positional argument: 'message' using Multiprocessing

python - 在 Django 中测试工作流程

unit-testing - 使用闭包对 GORM 调用进行单元测试

c# - 单元测试中的进度指示

javascript - 用于 jasmine/karma 测试的 angularjs 中的全局模拟对象

python - 将多个 csv 文件读取到单独的 pandas 数据帧中

python - 将 Pandas 堆积的 DataFrame 转换为 Matrix

unit-testing - 基本 block 覆盖——准确的定义是什么?

Python:Int() Base 10 的无效文字