Python 的单元测试有问题

Having an issue with Python's unittest

我正在学习 Python 并尝试测试我使用 unittest 编写的多项式 class。似乎我从直接 运行 Python 中的测试和 运行 使用 unittest 的测试中得到不同的结果,我不明白发生了什么。

import unittest
from w4_polynomial import Polynomial

class TestPolynomialClass(unittest.TestCase):

    def setUp(self):
        self.A = Polynomial()
        self.A[1] = 1
        self.A[2] = 2
        self.B = Polynomial()
        self.B[1234] = 5678

    def test_assertNotEq(self):
        self.C = Polynomial()
        self.C[1234] = 5678
        self.C[1] = 1
        self.C[2] = 3
        self.assertNotEqual(self.A+self.B, self.C)

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

单元测试失败...但我不明白为什么。这两个多项式不一样。以下是在 python 脚本中使用 print 进行比较的相同测试的结果。多项式不同,但结果相同:

A+B =    442x^123 + 12x^6 + 12x^4 + 5x^1 + 0x^0 + -99x^-12 
C =      442x^123 + 12x^6 + 12x^4 + 5x^1 + 0x^0 + 99x^-12 
A+B==C is  False

如果能帮助解释发生了什么,我们将不胜感激。

抱歉忘记了单元测试的错误,

    FAIL: test_assertEq (__main__.TestPolynomialClass)
----------------------------------------------------------------------
Traenter code hereceback (most recent call last):
  File "add.py", line 18, in test_assertEq
self.assertNotEqual(self.A+self.B, self.C)
AssertionError: <w4_polynomial.Polynomial object at 0x7f2d419ec390> == <w4_polynomial.Polynomial object at 0x7f2d419ec358>

现在多项式Class:

class Polynomial():

def __init__(self, value=[0]):
    self.v = []
    self.n = []
    temp = list(reversed(value[:]))
    if value == [0]:
        self[0] = 0
    else:
        for x in range(0, len(temp)):
            self[x] = temp[x]
    #self.__compress()

...

def __eq__(self, value):
    temp1 = self.v[:]
    temp2 = self.n[:]
    temp3 = value.v[:]
    temp4 = value.n[:]
    temp1.sort()
    temp2.sort()
    temp3.sort()
    temp4.sort()
    return (temp1 == temp3 and temp2 == temp4)

def __ne__(self, value):
    temp1 = self.v[:]
    temp2 = self.n[:]
    temp3 = value.v[:]
    temp4 = value.n[:]
    temp1.sort()
    temp2.sort()
    temp3.sort()
    temp4.sort()
    return (temp1 != temp3 and temp2 != temp4)

...

def main():
    pass

if __name__=="__main__":
    main()

我认为问题在于多项式 class 中 def __ne__ 函数的实现。 调用 assertNotEqual 时,如果传递的值不相等,则需要一个 True 值。但是在这个 class 中,您直接发送 temp1 != temp3 和 temp2 != temp4.

的输出

所以,函数应该是这样的

def __ne__(self, value):
    temp1 = self.v[:]
    temp2 = self.n[:]
    temp3 = value.v[:]
    temp4 = value.n[:]
    temp1.sort()
    temp2.sort()
    temp3.sort()
    temp4.sort()
    result = True if not (temp1 != temp3 and temp2 != temp4) else False
    return result