[TIP] dicts in doctests
Nicolas Chauvat
nicolas.chauvat at logilab.fr
Fri Sep 19 10:06:43 PDT 2008
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.
--
Nicolas Chauvat
logilab.fr - services en informatique scientifique et gestion de connaissances
More information about the testing-in-python
mailing list