Design advice for unit test asserters

Kent Johnson kent37 at tds.net
Thu Apr 21 08:52:46 EDT 2005


Gary wrote:
> 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 ]

Personally I avoid using list comprehensions with side-effects; if I don't actually want the list I 
write it out:
   for f in fileList:
     self.AssertFileExists(f)

> 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)

I would write this method to actually do the assertion:
      def AssertIsTypeQ(theObjectBeingTested, rawFileInfo):
          someComputedFile = DoStuff(rawFileInfo)
          self.assert_(theObjectBeingTested.isFileTypeQ(someComputedFile))

and then call it from within various tests as:
       self.AssertIsFileTypeQ(myObject, someFile)

I think of it as extending the standard assertions with domain-specific ones.

I often write methods called checkSomething() that do a bit of work and check the result. So I might 
  actually call the above method something like checkDoStuffIsFileTypeQ().

So, the convention I use is
- write assertSomething() primitives that just check a condition
- write checkSomething() methods that do some work and check the result
- build the actual tests using the above

Kent



More information about the Python-list mailing list