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

Cameron Simpson cs at zip.com.au
Fri Apr 23 08:15:16 CEST 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, value.name)
|       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 sqla.py module from the same
place as the node.py where the test lives, and likewise in sqla.py
to relatively import node.py 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 zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

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



More information about the Python-list mailing list