Design advice for unit test asserters

Gary gfyho at yahoo.com
Thu Apr 21 08:06:20 EDT 2005


I'm working on a project where I'm doing various file manipulations.
I'm not familiar with the idioms are common or good for this situation,
so I'd appreciate advice and suggestions.

Question 1:  A number of checks apply to a set of files.  So I'm
wondering whether to have something like:

     def test_SomeTest(...):
         ...
         self.AssertAllFilesExist(fileList)

or

     def test_SomeTest(...):
         ...
         [ self.AssertFileExists(f) for f in fileList ]

In a statically typed, tiny method design approach, the former would be
preferred.  But in Python the latter seems easy enough and more
natural.  And I'm wondering if I'm missing some other Python idiom that
would be even better.

Question 2:  A more complicated example:  My object defines its own
conditions that can be queried, e.g.

     def test_SomeTest(...):
         myObject.DoSomething()
         self._assert(myObject.isFileTypeQ(someFile))

but the parameter someFile is often an expression that should be
encapsulated into the assertion.  This gives me two possibilities:  I
can define a stand-alone query that takes myObject as a parameter:

     def AssertIsTypeQ(theObjectBeingTested, rawFileInfo):
         someComputedFile = DoStuff(rawFileInfo)
         return theObjectBeingTested.isFileTypeQ(someComputedFile)

and then call it from within various tests as:

     self._assert(AssertIsFileTypeQ(myObject, someFile)

or I can define an intermediate unit test case:

     class myTester(unittest.TestCase):
        def AssertIsFileTypeQ(self, rawFileInfo):
          someComputedFile = DoStuff(rawFileInfo)
          self.theObject.isFileTypeQ(someComputedFile)

and then define my test cases as

     class test_MyObjectX(myTester):

       def test_Sometest():
          self.theObject = ClassBeingTested()
          self.theObject.DoSomething()
          self.AssertIsFileTypeQ(someFile)

With these simple cases, this seems like six of one and a half dozen of
the other.  But the problem grows, in that there are several of these
assertions, and they often need to be applied to lists of things.  At
one point I was getting really complicated by abstracting out both the
looping and the computed file names, passing in a functor containing
the simple test and the name (for the message).  I gave up on this and
now I'm leaning towards the first, but again, I wonder if I'm missing a
better or more natural way to solve this problem.

Thanks,

Gary




More information about the Python-list mailing list