Skip to content

Commit c21af30

Browse files
committed
added unittest for addition
1 parent b2743ab commit c21af30

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

exercises/vector/solution/vector.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@ def __add__(self, other):
6363
try:
6464
if len(self) != len(other):
6565
raise ValueError('Only vectors of same length may be added.')
66+
return Vector(a + b for a, b in zip(self, other))
6667
except TypeError:
6768
return NotImplemented
68-
return Vector(a + b for a, b in zip(self, other))
6969

7070
def __radd__(self, other):
7171
return self + other
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import unittest
2+
3+
from vector import Vector
4+
5+
class TestAddition(unittest.TestCase):
6+
7+
8+
def setUp(self):
9+
self.v2d = Vector([1, 2])
10+
11+
12+
def test_2d_vector_addition(self):
13+
v = Vector([3, 4]) + self.v2d
14+
self.assertEqual(v, Vector([4, 6]))
15+
16+
17+
def test_mismatched_lengths_exception(self):
18+
v = Vector([1, 2, 3])
19+
with self.assertRaises(ValueError):
20+
v + self.v2d
21+
22+
23+
def test_not_implemented_exception(self):
24+
with self.assertRaises(TypeError) as exc:
25+
self.v2d + 1
26+
assert 'unsupported operand' in str(exc.exception)
27+
28+
29+
def test_reversed_operator(self):
30+
v = [10, 20] + self.v2d
31+
self.assertEqual(v, Vector([11, 22]))

0 commit comments

Comments
 (0)