Method to separate unit-test methods and data?

Lie Ryan lie.1296 at gmail.com
Tue Jul 7 06:08:14 EDT 2009


Nick Daly wrote:
> Hi,
> 
> 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.
> 
<snip>
> 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.
> 

It is usually not a very good idea to complicate the testing framework
with configuration files (as then you will have two things to be
tested). Unless the testing data is very huge (so huge that it
interferes with reading and writing the testing code), and huge data is
necessary for the test, it is much simpler and better to just put the
data into the test code. In cases where you want to have fairly complex
object (list, etc) you can "import" the test data. Pickling is usually
unnecessary unless you want to store instance data (classes, etc).

-- code.py --
def add(a, b):
    return a + b

-- test.py --
import unittest

# import the file we're testing
import code

# imports the data from separate file
from testdata import data

class AddCase(unittest.TestCase):
    def test_add():
        for case in data:
            self.assertEqual(code.add(case[0], case[1]), case[2])

-- testdata.py --
data = [(0, 0, 0),
        (1, 0, 1),
        (0, 1, 1),
        (1, -1, 0),
       ]



More information about the Python-list mailing list