当结果相等时 Python 单元测试失败 [英] Python unittest failure when results appear equal

查看:28
本文介绍了当结果相等时 Python 单元测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm running a series of unit tests on an RPN calculator I've just put together. This calculator can mix integers, floats, and picas. I often need to be able to calculate using picas for some typesetting work I'm doing.

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

For some reason, one of my unit tests is failing:

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']

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

I can't see why. To simplify I took the list out of the equation and compared directly to a string:

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 中运行,如果我点击查看差异,它告诉我没有差异,内容相同,但测试失败.它也从命令行失败.

It still fails. I cannot see why '8p2' != '8p2'. Running in PyCharm if I click to see the difference, it tells me there are no differences, and the content is identical, yet the test fails. It fails from the command line as well.

我已经进行了与 doctest 相同的测试:

I've put the same test in as a 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 运行此程序时,出现以下错误:

When I run this with Python 3.5, I get the following error:

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 字符串时有效的编码,这就是为什么即使它们具有不同的类型,它们也打印相同的编码:

Ok, I found the difference. Python 3 has more support for unicode, but it doesn't show the encoding that is in effect when printing a unicode string, which is why they printed the same even though they had different types:

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

In order for the assertion to work, either a smarter compare is needed, or else the strings need to be put in a common format before calling the assert methods.

这篇关于当结果相等时 Python 单元测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆