How do I test dictionary-equality with Python's doctest-package?

前端 未结 7 1478
眼角桃花
眼角桃花 2020-12-09 07:15

I\'m writing a doctest for a function that outputs a dictionary. The doctest looks like

>>> my_function()
{\'this\': \'is\', \'a\': \'dictionary\'}
         


        
7条回答
  •  借酒劲吻你
    2020-12-09 08:01

    You can create an instance of unittest.TestCase class inside your doctests, and use it to compare dictionaries:

    def my_function(x):
        """
        >>> from unittest import TestCase
        >>> t = TestCase()
    
        >>> t.assertDictEqual(
        ...     my_function('a'),
        ...     {'this': 'is', 'a': 'dictionary'}
        ... )
    
        >>> t.assertDictEqual(
        ...     my_function('b'),
        ...     {'this': 'is', 'b': 'dictionary'}
        ... )
    
        """
        return {'this': 'is', x: 'dictionary'}
    

    Note: this approach is better than simply checking if dictionaries are equal, because it will show diff between the two dictionaries.

提交回复
热议问题