[TIP] dicts in doctests

Matt Good matt at matt-good.net
Sat Sep 20 14:15:40 PDT 2008


On Sep 19, 2008, at 10:06 AM, Nicolas Chauvat wrote:

> On Wed, Sep 17, 2008 at 07:43:43PM -0500, Pete wrote:
>> Hiya-
>>
>> Is there a preferred way of testing dicts in doctests?  The random  
>> key
>> ordering can be problematic (IIRC, this bit the django port to  
>> Jython).
>>
>>>>> dict([('x', 1), ('y', 2)])
>> {'x': 1, 'y': 2}
>>
>> Python doesn't guarantee what order the dict is printed in.  It'd be
>> possible to work around like so:
>>
>>>>> dict([('x', 1), ('y', 2)]) == {'x': 1, 'y': 2}
>> True
>>
>> or even
>>
>>>>> d = dict([('x', 1), ('y', 2)])
>>>>> sorted(d.items())
>> [('x': 1), ('y': 2)]
>>
>> But both of these approaches kinda defeat the tests as documentation
>> benefit.
>>
>> Any thoughts?  Just go with the first case & hope for the best?  The
>> ordering's relatively stable across CPythons (versions & platforms)
>> AFAIK...
>
> from logilab.common.testlib import TestCase
>
> class MyTestCase(TestCase):
>
>      def test_me(self):
>          self.assertDictEquals({1:'one'}, {2:'two'})
>
> will provide a nice error message if the assertion fails.

Yes, but that doesn't work with doctest.

-- Matt



More information about the testing-in-python mailing list