question about an exciting gotcha for unittests (and elsewhere) ...

Cameron Simpson cs at
Fri Apr 23 02:15:16 EDT 2010

On 23Apr2010 15:37, I wrote:
|   class Backend(object):
|     def serialise(self, value):
|       ''' Convert a value for external string storage.
|       '''
|       if isinstance(value, Node): [...]
|         return ":%s:%s" % (value.type,
|       t = type(value)
|       assert t in (str,int), repr(t)+" "+repr(value)+" "+repr(Node)
|       [...]
|   AssertionError: <class '__main__.Node'> HOST:foo:{} <class 'cs.nodedb.node.Node'>
| Experienced users will see at once what's happened: I've made a Node
| myself in the test using the local class, and the Node class is thus
| __main__.Node. However, my sql Backend class has independently imported
| the "Node" and "Backend" classes from "cs.nodedb.node". So when _it_
| calls serialise(), "Node" is "cs.nodedb.node.Node".

A walk around the block and I'm thinking the olny sane way to do this is
to use relative imports, to always get the module from the same
place as the where the test lives, and likewise in
to relatively import to get its matching file.

And then to explicitly import from "node" etc in the test to get the
right names.

However, that means the unit test knows its own filename/module-name.

This doesn't feel totally nice.

Remarks, anyone?
Cameron Simpson <cs at> DoD#743

I have an inferiority complex, but it isn't a very good one.
        - Bill Garrett <garrett at>

More information about the Python-list mailing list