unittest: How to fail if environment does not allow execution?

Roy Smith roy at panix.com
Thu May 11 07:54:19 EDT 2006


Kai Grossjohann <kai.grossjohann at verizonbusiness.com> wrote:
> I am trying to figure out whether a message is logged by syslog.
> Not sure how I would do that except require the user to configure syslog
> to log foo messages to the /var/log/foo file and to then check that
> the message is written.

Well, I suppose that depends on what exactly it is that you're trying to 
test.  Are you testing the operation of the syslog system itself, or are 
you testing that *your program* calls syslog at the appropriate time?  If 
the latter, then you might consider writing your own test stub replacement 
for the syslog module that looks something like this:

history = []

def clearHistory():
   global history
   history = []

def syslog (arg1, args=None):
   history.append ((time.ctime(), arg1, arg2))

Arrange to have this module be found in your PYTHONPATH before the standard 
one.  Have your setUp() method call clearHistory().  Each test case that 
should write something to syslog can interrogate syslog.history to see if 
the appropriate thing was added to the list.

There is so much that can go wrong with syslog that it's hard to do any 
deterministic testing using it.  The syslogd could crash.  It could be 
configured wrong (or in a way which forwards all local syslog messages to 
another machine).  Or, the UDP messages could just plain get dropped by the 
network without a trace.  This is not the kind of stuff you want to be 
trusting for a unit test.

> Why did you use the open/IOError combination, instead of
> os.stat/OSError?  I am using the latter.  But I don't know what I'm doing...

I simply tried opening a non-existent file and saw what exception I got:

>>> open ("/dev/foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: '/dev/foo'
>>> 

I suppose it would have been smarter to have read the docs, but I'm lazy.  
Larry Wall says that's a good thing in programmers :-)



More information about the Python-list mailing list