6

Writing doctests for a method that abbreviates a dictionary by searching for a passed key word in the keys of the original dictionary, and returning the new, abbreviated dictionary. My docstring looks as follows:

def abbreviate_dict(key_word, original_dict):
    """
    >>> orig_dict = {apple_stems: 2, apple_cores: 5, apple_seeds: 3}
    >>> abbreviate_dict('apple', orig_dict)
    {'cores': 5, 'seeds': 3, 'stems': 2}
    """
   etc.
   return new_dict

The function works, but when I run py.test's doctest, the function fails the test as it returns the strings as unicode. I do not programmatically switch the strings to unicode in my function, but I am aware that python 2.7 returns in unicode.

Expected:
    {'cores': 5, 'seeds': 3, 'stems': 2}
Got:
    {u'cores': 5, u'seeds': 3, u'stems': 2}

How can I can I get the doctest to acknowledge that unicode and regular string outputs are the same?

af3ld
  • 782
  • 8
  • 30
  • "How can I can I get the doctest to acknowledge that unicode and regular string outputs are the same?" - bad move. They're not at all the same. It's very important to always be aware whether you're working with bytestrings or Unicode strings. – user2357112 Jun 22 '16 at 18:03
  • On the other hand, Python 2/3 compatibility can be difficult to achieve with doctests, since the string types display differently on Python 2 and 3. – user2357112 Jun 22 '16 at 18:05
  • They are not the same, but the focus of the function is not to decipher between types of strings, but instead manipulate and return a dictionary. I want to see if the right dictionary is returned, how can guide the test to check congruency between the output of the function? – af3ld Jun 22 '16 at 18:12

1 Answers1

6

You can set the ALLOW_UNICODE flag (either globally or per test), see the pytest docs for details.

Example:

[pytest]
doctest_optionflags = ALLOW_UNICODE

or

# content of example.rst
>>> get_unicode_greeting()  # doctest: +ALLOW_UNICODE
'Hello'
The Compiler
  • 11,126
  • 4
  • 40
  • 54
  • A useful answer. Not sure why there are so many answers to related questions along the lines of 'Doctest can't do this and is lame, don't use it.' :( – jwg Sep 22 '17 at 01:46