Iterating over test data in unit tests
Steven Bethard
steven.bethard at gmail.com
Tue Dec 6 01:50:42 EST 2005
Ben Finney wrote:
> Maybe I need to factor out the iteration into a generic iteration
> function, taking the actual test as a function object. That way, the
> dataset iterator doesn't need to know about the test function, and
> vice versa.
>
> def iterate_test(self, test_func, test_params=None):
> """ Iterate a test function for all the sets """
> if not test_params:
> test_params = self.game_params
> for key, params in test_params.items():
> dataset = params['dataset']
> instance = params['instance']
> test_func(key, dataset, instance)
>
> def test_score_throws(self):
> """ Game score should be calculated from throws """
> def test_func(key, dataset, instance):
> score = dataset['score']
> for throw in dataset['throws']:
> instance.add_throw(throw)
> self.failUnlessEqual(score, instance.get_score())
>
> self.iterate_test(test_func)
>
> That's somewhat clearer; the test function actually focuses on what
> it's testing. Those layers of indirection are annoying, but they allow
> the data sets to grow without writing more code to handle them.
Don't know if this helps, but I'd be more likely to write this as
something like (untested)::
def get_tests(self, test_params=None):
""" Iterate a test function for all the sets """
if not test_params:
test_params = self.game_params
for key, params in test_params.items():
dataset = params['dataset']
instance = params['instance']
yield key, dataset, instance
def test_score_throws(self):
""" Game score should be calculated from throws """
for key, dataset, instance in self.get_tests()
score = dataset['score']
for throw in dataset['throws']:
instance.add_throw(throw)
self.failUnlessEqual(score, instance.get_score())
That is, make an interator to the various test information, and just put
your "test_func" code inside a for-loop.
STeVe
More information about the Python-list
mailing list