对Python的unittes有问题吗

2024-09-24 04:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python并尝试测试我用unittest编写的多项式类。似乎我从直接用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()

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

^{pr2}$

如果你能帮我解释一下发生了什么事,我将不胜感激。在

抱歉忘记了unittest的错误

    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 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()

Tags: testselfifvaluemaindefunittestsort
1条回答
网友
1楼 · 发布于 2024-09-24 04:17:23

我认为问题在于多项式类中def __ne__函数的实现。 调用assertNotEqual时,当传递的值不相等时,应为真值。但是在这个类中,您直接发送temp1的输出!=温度3和温度2!=温度4。在

所以,函数应该是这样的

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

相关问题 更多 >