结果相等时 Python 单元测试失败

标签 python unit-testing python-unittest

我正在我刚刚组装的 RPN 计算器上运行一系列单元测试。这个计算器可以混合使用整数、 float 和派卡。对于我正在做的一些排版工作,我经常需要能够使用 picas 进行计算。

出于某种原因,我的一个单元测试失败了:

Failure
Traceback (most recent call last):
  File "/Users/andrew/Developer/pyRpn/test_rpn.py", line 112, in test_pica_subtracted_from_pica
    self.assertEqual(self.calc.rpn(['10p3', '2p1', '-']), ['8p2'])
AssertionError: Lists differ: ['8p2'] != ['8p2']

First differing element 0:
'8p2'
8p2

  ['8p2']

我不明白为什么。为了简化,我将列表从等式中取出并直接与字符串进行比较:

Failure
Expected :'8p2'
Actual   :'8p2'
 <Click to see difference>

Traceback (most recent call last):
  File "/Users/andrew/Developer/pyRpn/test_rpn.py", line 112, in test_pica_subtracted_from_pica
    self.assertEqual(self.calc.rpn(['10p3', '2p1', '-']).pop(), '8p2')
AssertionError: '8p2' != '8p2'

还是失败了。我不明白为什么 '8p2' != '8p2'。在PyCharm中运行点击查看区别,它告诉我没有区别,内容相同,但测试失败。它也从命令行失败。

我已经将相同的测试作为 doctest:

"""
>>> RPN().rpn(['10p3', '2p1', '-'])
['8p2']
"""

它毫无问题地通过了。


MCVE:

import re
import unittest


class Pica(object):
    def __init__(self, points):
        self.points = points

    def __repr__(self):
        whole_points = int(self.points / 12)
        sub_points = self.points - (whole_points * 12)
        return "'%rp%r'" % (whole_points, sub_points)

    def __sub__(self, other):
        if type(other) is Pica:
            return Pica(self.points - other.points)


class RPN:
    def __init__(self):
        self.oper_dict = {'-': RPN.pop_two_and_sub}
        self.pica_pattern = re.compile("(\d+)p(\d+)")

    def pop_two_and_sub(self, terms):
        terms.append(terms.pop() - terms.pop())

    def rpn(self, terms):
        result = []
        for term in terms:
            if term in self.oper_dict:
                self.oper_dict[term](self, result)
            elif self.pica_pattern.match(term):
                match = self.pica_pattern.match(term)
                result.append(Pica(int(match.group(1)) * 12 + int(match.group(2))))
            else:
                raise SyntaxError
        return result


class TestPica(unittest.TestCase):
    def test_pica_subtracted_from_pica(self):
        self.assertCountEqual(RPN().rpn(['2p1', '10p3', '-']), ['8p2'])


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

当我使用 Python 3.5 运行它时,出现以下错误:

Failure
Traceback (most recent call last):
  File "/Users/andrew/Developer/pyRpn/mvce.py", line 42, in test_pica_subtracted_from_pica
    self.assertCountEqual(RPN().rpn(['2p1', '10p3', '-']), ['8p2'])
AssertionError: Element counts were not equal:
First has 1, Second has 0:  '8p2'
First has 0, Second has 1:  '8p2'

最佳答案

好的,我发现了不同之处。 Python 3 对 unicode 有更多的支持,但它没有显示打印 unicode 字符串时有效的编码,这就是为什么即使它们具有不同的类型也打印相同的原因:

  1. <class '__main__.Pica'>
  2. <class 'str'>

为了使断言起作用,要么需要更智能的比较,要么在调用断言方法之前将字符串置于通用格式中。

关于结果相等时 Python 单元测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35648864/

相关文章:

python - 测试 Django 信号的正确方法

Python单元测试多线程

python - 查找列表中的元素

python - Django/unittest 在测试运行程序末尾运行命令

python - 使用相似的列合并 2 个数据框

python - 计算 Python 列表列表中元素的频率

python - 在 Python 中将 SQL 转换为 json

java - 如何告诉 android testrunner 测试 external.apk 而不是生成的 app-debug.apk?

Python unittest 成功断言 None 为 False

python - 向 kivy 按钮添加 on_release Action