Search code examples
pythonpython-2.7testingpytestdoctest

Python: accept unicode strings as regular strings in doctests


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?


Solution

  • 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'