如何在unittest中执行交叉乘法



我有以下类

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

,我试图使用单元测试功能如下:

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) 

它对交叉乘法之前的所有测试都很有效。我想听听你对如何设置的建议。另外,我不知道如何设置哈希测试。请让我知道如果你可能建议一些方法来解决这个问题。

Thank you so much

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

现在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)]

最新更新