如何在unittest中执行交叉乘法

How to execute the cross multiplication in unittest

我有以下class

from math import sqrt

class Vector:

  def __init__(self, x, y, z):   
    self.x = x
    self.y = y
    self.z = z
    
  def __eq__(self, other):   # v == w
        return self.x == other.x and self.y == other.y and self.z == other.z

  def __ne__(self, other):        # v != w
        return not self == other    

  def __repr__(self): 
    return "Vector(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")"

  def __add__(self, other):
    return Vector(self.x + other.x,self.y + other.y,self.z + other.z)

  def __sub__(self, other):
    return Vector(self.x - other.x, self.y - other.y, self.z - other.z)

  def __mul__(self, other):  
    return self.x * other.x + self.y * other.y + self.z * other.z
  
  def cross(self, other):
    return Vector(self.y * other.z - self.z * other.y,self.z * other.x - self.x * other.z,self.x * other.y - self.y * other.x)

  def length(self):
    return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)

  def __hash__(self): 
    return hash((self.x, self.y, self.z))

我正在尝试使用 unittest 函数,如下所示:

class TestVector(unittest.TestCase):
    # test function to test equality of two value
    
    def test_vector_equality(self):
        A = [1, 2, 3]
        B = [1, 2, 3]
        # error message in case if test case got failed
        #message = "First value and second value are not equal!"
        self.assertTrue(A == B)
        
    def test_vector_inequality(self):
        A = [1, 2, 3]
        B = [1,-2,-3]
        self.assertFalse(A == B)  
    
    def test_vector_addition(self):
        A = [1, 2, 3]
        B = [1, 2, 3]
        result = [2, 4, 6]
        self.assertEqual([x + y for x, y in zip(A, B)], result) 

    def test_vector_mulitplication(self):
        A = [1, 2, 3]
        B = [1, 2, 3]
        result = [1, 4, 9]
        self.assertEqual([x*y for x, y in zip(A, B)], result)
    
    def test_vector_subtraction(self):
        A = [1, 2, 3]
        B = [1, 5, 8]
        result = [0, -3, -5]
        self.assertEqual([x - y for x, y in zip(A, B)], result) 
        
    def test_vector_cross_multiplication(self):
        A = [1, 2, 3]
        B = [1, 5, 8]
        result = [1 ,5, 3]
        self.assertEqual([(x[0]*y[1], x[1]*y[0]) for x, y in zip(A, B)], result)
        
    def test_length(self):
        A = [1, 2, 3]
        B = [1, 4, 9] 
        self.assertEqual(B, [i ** 2 for i in A])          
                                                 
if __name__ == "__main__":
    unittest.main(argv=['first-arg-is-ignored'], exit= False) 

它适用于交叉乘法之前的所有测试。我想得到一些关于如何设置它的建议。另外,我不知道如何设置哈希测试。请告诉我您是否可以提出一些解决此问题的方法。

非常感谢

与问题无关,但很重要:这不是单元测试的方式。测试预计将使用 class 方法,将结果与预期结果进行比较。

现在 test_vector_cross_multiplication 的问题:

  • 结果应该是 [1, -5, 3] 而不是 [1, 5, 3]
  • 理解[(x[0]*y[1], x[1]*y[0]) for x, y in zip(A, B)] 使用数字索引并生成元组

叉积的正确计算方法:

[(A[i]*B[i+1] - B[i]*A[i+1]) for i in range(1-len(A), 1)]