I have the following 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))
on which I am trying to use the unittest function as follows:
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)
It works great for all the tests before the cross multiplication one. I would like to get some suggestions about how to set it. Also, I do not know how to set the hash test. Just let me know if you possibly might suggest some way to fix this.
Thank you so much
CodePudding user response:
Unrelated to the question, but imporant: this is not how you unittest. Tests are expected to use class methods, comparing results with expected ones.
Now the issues with test_vector_cross_multiplication
:
- the result should be
[1, -5, 3]
instead of[1, 5, 3]
- the comprehension
[(x[0]*y[1], x[1]*y[0]) for x, y in zip(A, B)]
uses indexes on numbers and produces tuples
The correct way to calculate the cross product:
[(A[i]*B[i 1] - B[i]*A[i 1]) for i in range(1-len(A), 1)]