Reputation: 5446
I have made a simple generator in Python, it is under a file called program.py
class Loop():
def __init__(self):
self.i=1
def __iter__(self):
return self
def next(self):
if self.i>10:
raise StopIteration
self.i=self.i+1
return self.i
I have made a unittest module so that it tests the iterator and when there is a number 5 on the list then it prints that the test has failed in that part. I have do something like this:
class TestA(unittest.TestCase):
def test(self):
for x in Loop():
if not self.assertRaises(AssertionError,self.assertEqual(x,5)):
print x
but I see that this breaks up after the first iteration, what am I doing wrong?
any help? Thanks
Upvotes: 0
Views: 803
Reputation: 9670
You're approaching the test incorrectly.
Your iterator is basically the equivalent of xrange
hardcoded to start from 2 and goes to infinity.
The reason it starts from 2
is because you're initialising i
to 1 and incrementing i
inside the next before returning the first value.
I would write the test as follows
class TestA(unittest.TestCase):
def test_loop_is_sliceable(self):
slc = itertools.islice(Loop(), 5)
self.assertEqual(range(2, 7), list(slc))
Also note that asserts are not predicates so they don't give you back a bool to use in conditional statements.
Upvotes: 1