Method to separate unit-test methods and data?

Nick Daly nick.m.daly at
Sun Jul 5 20:48:06 CEST 2009


I was wondering if it's possible / if there are any simple methods
known of storing unit-test functions and their data in separate files?

Perhaps this is a strange request, but it does an excellent job of
modularizing code.  As far as revision control goes, it makes it
easier to discern between new or changed test cases, and changes in
the test data.

I've worked through this idea a bit and actually have a nearly working
model.  For example, when testing a class, I have a test module, which
contains a class for testing each method of the class.  This allows me
to generalize each method's parameters into each class, which can then
be overridden by the config file's data, something like as follows
(with a really arbitrary example, Python 2.5 code):

Demo code (

class Midpoint(object):

   def __init__(self, a, b):
       self.a = a
       self.b = b

   def mid():
       return (self.a + self.b) / 2.0

   def sum()
       return (self.a + self.b)

Testing Code (

import unittest
import midpoint
import sys, ConfigParser as configparser

# set up the config file that overrides each class's data
config = configparser.SafeConfigParser()[0])

class test_Midpoint_mid(unittest.TestCase):
   def __init__(self):

       # default testing values
       self.none_values = ((None, 1),
                           (0, None))

       # override the default values with the config file values
       for key, value in config.items(self.__class__.__name__):
           if value:
               setattr(self, key, value)

   # a few tests of the method
   def test_rejectNone(self):
       for tests in self.none_values:
               midpoint.Midpoint(tests[0], tests[1]).mid)

# and repeat the concept for class test_Midpoint_sum

Config Code (test_Midpoint.cfg):

# override the default values of the test class's members

none_values = ((-1, None),
              (None, -12.8))

What I haven't yet figured out how to do though, is properly override
the default class member values with values from the config file.  The
config file's data is loaded as a string instead of as a list, as I'd
want.  This causes all the tests to fail, as while none_values needs
to be interpreted as a list, it is instead understood as:

" ((-1, None),\n               (None, -12.8))"

Does anyone have any solutions for these problems?  First, is there a
known and simple way to separate unit-test data and methods into
separate files?  Secondly, if not, is there a simple way to convert
strings into other base types, like lists, dictionaries, and so forth?
Or, am I going to have to write my own list-parsing methods?  Would
pickling help?  I haven't yet had a chance to look into if or how that
would work...  If there's anything else I can clarify about this
request, feel free to let me know.

Thanks for any help you can provide,

More information about the Python-list mailing list