I programmed a very simple generator in Python 3.4:
class Gen:
def __init__(self, xml_lines, attribs):
#...
def _get_values(self, xml_line):
# get only specific "attribs" from a line in a "xml"
def values(self):
for line in self.xml_lines:
yield self._get_values(line)
The code works when I use a for loop to consume the generated values:
reader = Gen(...):
for v in reader.values():
print(v)
But I'm now trying to create a unit test, and for that, I'd need to get each value at a time (outside a loop). I'm trying something like this:
import unittest
#...
reader = Gen(...):
v = reader.values()
self.assertIsNone(v)
When I try that, I always get a
AssertionError: <generator object next_values at 0x7fe2a5f9e3f0> is not None
So, when I call the values myself, it return something (is it a pointer?) instead of the generated value.
As I'm considering I'm using a basic generator pattern, my question is a little broader then my own code: what's the proper way to test a Python Generator?
You need to call next() or loop through the generator object to access the values produced by the generator expression. When there isn't the next value in the generator object, a StopIteration exception is thrown. A for loop can be used to iterate the generator object.
A test data generator is a specialized software tool that generates false or mock data for use in testing software applications. The generated data may be either random or specifically chosen to create a desired result.
Python generators are a simple way of creating iterators. All the work we mentioned above are automatically handled by generators in Python. Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
A generator is meant to be iterated through. You can use the next() function to get the next value of the generator. Be aware that if your generator has exhausted it's values, it will raise a StopIteration
exception.
reader = Gen(...):
values = reader.values()
v = next(values)
self.assertIsNone(v)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With