Best Python code snippet using autotest_python
test_pprint.py
Source:test_pprint.py  
1# -*- coding: utf-8 -*-2import collections3import io4import itertools5import pprint6import random7import test.support8import test.test_set9import types10import unittest11# list, tuple and dict subclasses that do or don't overwrite __repr__12class list2(list):13    pass14class list3(list):15    def __repr__(self):16        return list.__repr__(self)17class tuple2(tuple):18    pass19class tuple3(tuple):20    def __repr__(self):21        return tuple.__repr__(self)22class set2(set):23    pass24class set3(set):25    def __repr__(self):26        return set.__repr__(self)27class frozenset2(frozenset):28    pass29class frozenset3(frozenset):30    def __repr__(self):31        return frozenset.__repr__(self)32class dict2(dict):33    pass34class dict3(dict):35    def __repr__(self):36        return dict.__repr__(self)37class Unorderable:38    def __repr__(self):39        return str(id(self))40# Class Orderable is orderable with any type41class Orderable:42    def __init__(self, hash):43        self._hash = hash44    def __lt__(self, other):45        return False46    def __gt__(self, other):47        return self != other48    def __le__(self, other):49        return self == other50    def __ge__(self, other):51        return True52    def __eq__(self, other):53        return self is other54    def __ne__(self, other):55        return self is not other56    def __hash__(self):57        return self._hash58class QueryTestCase(unittest.TestCase):59    def setUp(self):60        self.a = list(range(100))61        self.b = list(range(200))62        self.a[-12] = self.b63    def test_init(self):64        pp = pprint.PrettyPrinter()65        pp = pprint.PrettyPrinter(indent=4, width=40, depth=5,66                                  stream=io.StringIO(), compact=True)67        pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO())68        pp = pprint.PrettyPrinter(sort_dicts=False)69        with self.assertRaises(TypeError):70            pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True)71        self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1)72        self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0)73        self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1)74        self.assertRaises(ValueError, pprint.PrettyPrinter, width=0)75    def test_basic(self):76        # Verify .isrecursive() and .isreadable() w/o recursion77        pp = pprint.PrettyPrinter()78        for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, b"def",79                     bytearray(b"ghi"), True, False, None, ...,80                     self.a, self.b):81            # module-level convenience functions82            self.assertFalse(pprint.isrecursive(safe),83                             "expected not isrecursive for %r" % (safe,))84            self.assertTrue(pprint.isreadable(safe),85                            "expected isreadable for %r" % (safe,))86            # PrettyPrinter methods87            self.assertFalse(pp.isrecursive(safe),88                             "expected not isrecursive for %r" % (safe,))89            self.assertTrue(pp.isreadable(safe),90                            "expected isreadable for %r" % (safe,))91    def test_knotted(self):92        # Verify .isrecursive() and .isreadable() w/ recursion93        # Tie a knot.94        self.b[67] = self.a95        # Messy dict.96        self.d = {}97        self.d[0] = self.d[1] = self.d[2] = self.d98        pp = pprint.PrettyPrinter()99        for icky in self.a, self.b, self.d, (self.d, self.d):100            self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")101            self.assertFalse(pprint.isreadable(icky), "expected not isreadable")102            self.assertTrue(pp.isrecursive(icky), "expected isrecursive")103            self.assertFalse(pp.isreadable(icky), "expected not isreadable")104        # Break the cycles.105        self.d.clear()106        del self.a[:]107        del self.b[:]108        for safe in self.a, self.b, self.d, (self.d, self.d):109            # module-level convenience functions110            self.assertFalse(pprint.isrecursive(safe),111                             "expected not isrecursive for %r" % (safe,))112            self.assertTrue(pprint.isreadable(safe),113                            "expected isreadable for %r" % (safe,))114            # PrettyPrinter methods115            self.assertFalse(pp.isrecursive(safe),116                             "expected not isrecursive for %r" % (safe,))117            self.assertTrue(pp.isreadable(safe),118                            "expected isreadable for %r" % (safe,))119    def test_unreadable(self):120        # Not recursive but not readable anyway121        pp = pprint.PrettyPrinter()122        for unreadable in type(3), pprint, pprint.isrecursive:123            # module-level convenience functions124            self.assertFalse(pprint.isrecursive(unreadable),125                             "expected not isrecursive for %r" % (unreadable,))126            self.assertFalse(pprint.isreadable(unreadable),127                             "expected not isreadable for %r" % (unreadable,))128            # PrettyPrinter methods129            self.assertFalse(pp.isrecursive(unreadable),130                             "expected not isrecursive for %r" % (unreadable,))131            self.assertFalse(pp.isreadable(unreadable),132                             "expected not isreadable for %r" % (unreadable,))133    def test_same_as_repr(self):134        # Simple objects, small containers and classes that overwrite __repr__135        # For those the result should be the same as repr().136        # Ahem.  The docs don't say anything about that -- this appears to137        # be testing an implementation quirk.  Starting in Python 2.5, it's138        # not true for dicts:  pprint always sorts dicts by key now; before,139        # it sorted a dict display if and only if the display required140        # multiple lines.  For that reason, dicts with more than one element141        # aren't tested here.142        for simple in (0, 0, 0+0j, 0.0, "", b"", bytearray(),143                       (), tuple2(), tuple3(),144                       [], list2(), list3(),145                       set(), set2(), set3(),146                       frozenset(), frozenset2(), frozenset3(),147                       {}, dict2(), dict3(),148                       self.assertTrue, pprint,149                       -6, -6, -6-6j, -1.5, "x", b"x", bytearray(b"x"),150                       (3,), [3], {3: 6},151                       (1,2), [3,4], {5: 6},152                       tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),153                       [3,4], list2([3,4]), list3([3,4]), list3(range(100)),154                       set({7}), set2({7}), set3({7}),155                       frozenset({8}), frozenset2({8}), frozenset3({8}),156                       dict2({5: 6}), dict3({5: 6}),157                       range(10, -11, -1),158                       True, False, None, ...,159                      ):160            native = repr(simple)161            self.assertEqual(pprint.pformat(simple), native)162            self.assertEqual(pprint.pformat(simple, width=1, indent=0)163                             .replace('\n', ' '), native)164            self.assertEqual(pprint.saferepr(simple), native)165    def test_basic_line_wrap(self):166        # verify basic line-wrapping operation167        o = {'RPM_cal': 0,168             'RPM_cal2': 48059,169             'Speed_cal': 0,170             'controldesk_runtime_us': 0,171             'main_code_runtime_us': 0,172             'read_io_runtime_us': 0,173             'write_io_runtime_us': 43690}174        exp = """\175{'RPM_cal': 0,176 'RPM_cal2': 48059,177 'Speed_cal': 0,178 'controldesk_runtime_us': 0,179 'main_code_runtime_us': 0,180 'read_io_runtime_us': 0,181 'write_io_runtime_us': 43690}"""182        for type in [dict, dict2]:183            self.assertEqual(pprint.pformat(type(o)), exp)184        o = range(100)185        exp = '[%s]' % ',\n '.join(map(str, o))186        for type in [list, list2]:187            self.assertEqual(pprint.pformat(type(o)), exp)188        o = tuple(range(100))189        exp = '(%s)' % ',\n '.join(map(str, o))190        for type in [tuple, tuple2]:191            self.assertEqual(pprint.pformat(type(o)), exp)192        # indent parameter193        o = range(100)194        exp = '[   %s]' % ',\n    '.join(map(str, o))195        for type in [list, list2]:196            self.assertEqual(pprint.pformat(type(o), indent=4), exp)197    def test_nested_indentations(self):198        o1 = list(range(10))199        o2 = dict(first=1, second=2, third=3)200        o = [o1, o2]201        expected = """\202[   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],203    {'first': 1, 'second': 2, 'third': 3}]"""204        self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)205        expected = """\206[   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],207    {   'first': 1,208        'second': 2,209        'third': 3}]"""210        self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)211    def test_width(self):212        expected = """\213[[[[[[1, 2, 3],214     '1 2']]]],215 {1: [1, 2, 3],216  2: [12, 34]},217 'abc def ghi',218 ('ab cd ef',),219 set2({1, 23}),220 [[[[[1, 2, 3],221     '1 2']]]]]"""222        o = eval(expected)223        self.assertEqual(pprint.pformat(o, width=15), expected)224        self.assertEqual(pprint.pformat(o, width=16), expected)225        self.assertEqual(pprint.pformat(o, width=25), expected)226        self.assertEqual(pprint.pformat(o, width=14), """\227[[[[[[1,228      2,229      3],230     '1 '231     '2']]]],232 {1: [1,233      2,234      3],235  2: [12,236      34]},237 'abc def '238 'ghi',239 ('ab cd '240  'ef',),241 set2({1,242       23}),243 [[[[[1,244      2,245      3],246     '1 '247     '2']]]]]""")248    def test_sorted_dict(self):249        # Starting in Python 2.5, pprint sorts dict displays by key regardless250        # of how small the dictionary may be.251        # Before the change, on 32-bit Windows pformat() gave order252        # 'a', 'c', 'b' here, so this test failed.253        d = {'a': 1, 'b': 1, 'c': 1}254        self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")255        self.assertEqual(pprint.pformat([d, d]),256            "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")257        # The next one is kind of goofy.  The sorted order depends on the258        # alphabetic order of type names:  "int" < "str" < "tuple".  Before259        # Python 2.5, this was in the test_same_as_repr() test.  It's worth260        # keeping around for now because it's one of few tests of pprint261        # against a crazy mix of types.262        self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),263            r"{5: [[]], 'xy\tab\n': (3,), (): {}}")264    def test_sort_dict(self):265        d = dict.fromkeys('cba')266        self.assertEqual(pprint.pformat(d, sort_dicts=False), "{'c': None, 'b': None, 'a': None}")267        self.assertEqual(pprint.pformat([d, d], sort_dicts=False),268            "[{'c': None, 'b': None, 'a': None}, {'c': None, 'b': None, 'a': None}]")269    def test_ordered_dict(self):270        d = collections.OrderedDict()271        self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')272        d = collections.OrderedDict([])273        self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')274        words = 'the quick brown fox jumped over a lazy dog'.split()275        d = collections.OrderedDict(zip(words, itertools.count()))276        self.assertEqual(pprint.pformat(d),277"""\278OrderedDict([('the', 0),279             ('quick', 1),280             ('brown', 2),281             ('fox', 3),282             ('jumped', 4),283             ('over', 5),284             ('a', 6),285             ('lazy', 7),286             ('dog', 8)])""")287    def test_mapping_proxy(self):288        words = 'the quick brown fox jumped over a lazy dog'.split()289        d = dict(zip(words, itertools.count()))290        m = types.MappingProxyType(d)291        self.assertEqual(pprint.pformat(m), """\292mappingproxy({'a': 6,293              'brown': 2,294              'dog': 8,295              'fox': 3,296              'jumped': 4,297              'lazy': 7,298              'over': 5,299              'quick': 1,300              'the': 0})""")301        d = collections.OrderedDict(zip(words, itertools.count()))302        m = types.MappingProxyType(d)303        self.assertEqual(pprint.pformat(m), """\304mappingproxy(OrderedDict([('the', 0),305                          ('quick', 1),306                          ('brown', 2),307                          ('fox', 3),308                          ('jumped', 4),309                          ('over', 5),310                          ('a', 6),311                          ('lazy', 7),312                          ('dog', 8)]))""")313    def test_empty_simple_namespace(self):314        ns = types.SimpleNamespace()315        formatted = pprint.pformat(ns)316        self.assertEqual(formatted, "namespace()")317    def test_small_simple_namespace(self):318        ns = types.SimpleNamespace(a=1, b=2)319        formatted = pprint.pformat(ns)320        self.assertEqual(formatted, "namespace(a=1, b=2)")321    def test_simple_namespace(self):322        ns = types.SimpleNamespace(323            the=0,324            quick=1,325            brown=2,326            fox=3,327            jumped=4,328            over=5,329            a=6,330            lazy=7,331            dog=8,332        )333        formatted = pprint.pformat(ns, width=60)334        self.assertEqual(formatted, """\335namespace(the=0,336          quick=1,337          brown=2,338          fox=3,339          jumped=4,340          over=5,341          a=6,342          lazy=7,343          dog=8)""")344    def test_simple_namespace_subclass(self):345        class AdvancedNamespace(types.SimpleNamespace): pass346        ns = AdvancedNamespace(347            the=0,348            quick=1,349            brown=2,350            fox=3,351            jumped=4,352            over=5,353            a=6,354            lazy=7,355            dog=8,356        )357        formatted = pprint.pformat(ns, width=60)358        self.assertEqual(formatted, """\359AdvancedNamespace(the=0,360                  quick=1,361                  brown=2,362                  fox=3,363                  jumped=4,364                  over=5,365                  a=6,366                  lazy=7,367                  dog=8)""")368    def test_subclassing(self):369        o = {'names with spaces': 'should be presented using repr()',370             'others.should.not.be': 'like.this'}371        exp = """\372{'names with spaces': 'should be presented using repr()',373 others.should.not.be: like.this}"""374        self.assertEqual(DottedPrettyPrinter().pformat(o), exp)375    def test_set_reprs(self):376        self.assertEqual(pprint.pformat(set()), 'set()')377        self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')378        self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\379{0,380 1,381 2,382 3,383 4,384 5,385 6}''')386        self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\387set2({0,388      1,389      2,390      3,391      4,392      5,393      6})''')394        self.assertEqual(pprint.pformat(set3(range(7)), width=20),395                         'set3({0, 1, 2, 3, 4, 5, 6})')396        self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')397        self.assertEqual(pprint.pformat(frozenset(range(3))),398                         'frozenset({0, 1, 2})')399        self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\400frozenset({0,401           1,402           2,403           3,404           4,405           5,406           6})''')407        self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\408frozenset2({0,409            1,410            2,411            3,412            4,413            5,414            6})''')415        self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),416                         'frozenset3({0, 1, 2, 3, 4, 5, 6})')417    @unittest.expectedFailure418    #See http://bugs.python.org/issue13907419    @test.support.cpython_only420    def test_set_of_sets_reprs(self):421        # This test creates a complex arrangement of frozensets and422        # compares the pretty-printed repr against a string hard-coded in423        # the test.  The hard-coded repr depends on the sort order of424        # frozensets.425        #426        # However, as the docs point out: "Since sets only define427        # partial ordering (subset relationships), the output of the428        # list.sort() method is undefined for lists of sets."429        #430        # In a nutshell, the test assumes frozenset({0}) will always431        # sort before frozenset({1}), but:432        #433        # >>> frozenset({0}) < frozenset({1})434        # False435        # >>> frozenset({1}) < frozenset({0})436        # False437        #438        # Consequently, this test is fragile and439        # implementation-dependent.  Small changes to Python's sort440        # algorithm cause the test to fail when it should pass.441        # XXX Or changes to the dictionary implementation...442        cube_repr_tgt = """\443{frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}),444 frozenset({0}): frozenset({frozenset(),445                            frozenset({0, 2}),446                            frozenset({0, 1})}),447 frozenset({1}): frozenset({frozenset(),448                            frozenset({1, 2}),449                            frozenset({0, 1})}),450 frozenset({2}): frozenset({frozenset(),451                            frozenset({1, 2}),452                            frozenset({0, 2})}),453 frozenset({1, 2}): frozenset({frozenset({2}),454                               frozenset({1}),455                               frozenset({0, 1, 2})}),456 frozenset({0, 2}): frozenset({frozenset({2}),457                               frozenset({0}),458                               frozenset({0, 1, 2})}),459 frozenset({0, 1}): frozenset({frozenset({0}),460                               frozenset({1}),461                               frozenset({0, 1, 2})}),462 frozenset({0, 1, 2}): frozenset({frozenset({1, 2}),463                                  frozenset({0, 2}),464                                  frozenset({0, 1})})}"""465        cube = test.test_set.cube(3)466        self.assertEqual(pprint.pformat(cube), cube_repr_tgt)467        cubo_repr_tgt = """\468{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0,469                                                                                  2}),470                                                                       frozenset({0,471                                                                                  1,472                                                                                  2})}),473                                                            frozenset({frozenset({0}),474                                                                       frozenset({0,475                                                                                  1})}),476                                                            frozenset({frozenset(),477                                                                       frozenset({0})}),478                                                            frozenset({frozenset({2}),479                                                                       frozenset({0,480                                                                                  2})})}),481 frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0,482                                                                                  1}),483                                                                       frozenset({0,484                                                                                  1,485                                                                                  2})}),486                                                            frozenset({frozenset({0}),487                                                                       frozenset({0,488                                                                                  1})}),489                                                            frozenset({frozenset({1}),490                                                                       frozenset({1,491                                                                                  2})}),492                                                            frozenset({frozenset(),493                                                                       frozenset({1})})}),494 frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1,495                                                                                  2}),496                                                                       frozenset({0,497                                                                                  1,498                                                                                  2})}),499                                                            frozenset({frozenset({2}),500                                                                       frozenset({1,501                                                                                  2})}),502                                                            frozenset({frozenset(),503                                                                       frozenset({1})}),504                                                            frozenset({frozenset({1}),505                                                                       frozenset({0,506                                                                                  1})})}),507 frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1,508                                                                                  2}),509                                                                       frozenset({0,510                                                                                  1,511                                                                                  2})}),512                                                            frozenset({frozenset({1}),513                                                                       frozenset({1,514                                                                                  2})}),515                                                            frozenset({frozenset({2}),516                                                                       frozenset({0,517                                                                                  2})}),518                                                            frozenset({frozenset(),519                                                                       frozenset({2})})}),520 frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}),521                                                                 frozenset({0,522                                                                            1})}),523                                                      frozenset({frozenset({0}),524                                                                 frozenset({0,525                                                                            2})}),526                                                      frozenset({frozenset(),527                                                                 frozenset({1})}),528                                                      frozenset({frozenset(),529                                                                 frozenset({2})})}),530 frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(),531                                                                 frozenset({0})}),532                                                      frozenset({frozenset({1}),533                                                                 frozenset({1,534                                                                            2})}),535                                                      frozenset({frozenset(),536                                                                 frozenset({2})}),537                                                      frozenset({frozenset({1}),538                                                                 frozenset({0,539                                                                            1})})}),540 frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}),541                                                                 frozenset({1,542                                                                            2})}),543                                                      frozenset({frozenset(),544                                                                 frozenset({0})}),545                                                      frozenset({frozenset(),546                                                                 frozenset({1})}),547                                                      frozenset({frozenset({2}),548                                                                 frozenset({0,549                                                                            2})})}),550 frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1,551                                                                                        2}),552                                                                             frozenset({0,553                                                                                        1,554                                                                                        2})}),555                                                                  frozenset({frozenset({0,556                                                                                        2}),557                                                                             frozenset({0,558                                                                                        1,559                                                                                        2})}),560                                                                  frozenset({frozenset({0}),561                                                                             frozenset({0,562                                                                                        1})}),563                                                                  frozenset({frozenset({1}),564                                                                             frozenset({0,565                                                                                        1})})}),566 frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(),567                                                                       frozenset({0})}),568                                                            frozenset({frozenset({0,569                                                                                  1}),570                                                                       frozenset({0,571                                                                                  1,572                                                                                  2})}),573                                                            frozenset({frozenset({0}),574                                                                       frozenset({0,575                                                                                  2})}),576                                                            frozenset({frozenset({1}),577                                                                       frozenset({0,578                                                                                  1})})}),579 frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0,580                                                                                  2}),581                                                                       frozenset({0,582                                                                                  1,583                                                                                  2})}),584                                                            frozenset({frozenset({2}),585                                                                       frozenset({1,586                                                                                  2})}),587                                                            frozenset({frozenset({0}),588                                                                       frozenset({0,589                                                                                  2})}),590                                                            frozenset({frozenset(),591                                                                       frozenset({2})})}),592 frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1,593                                                                                        2}),594                                                                             frozenset({0,595                                                                                        1,596                                                                                        2})}),597                                                                  frozenset({frozenset({0,598                                                                                        1}),599                                                                             frozenset({0,600                                                                                        1,601                                                                                        2})}),602                                                                  frozenset({frozenset({0}),603                                                                             frozenset({0,604                                                                                        2})}),605                                                                  frozenset({frozenset({2}),606                                                                             frozenset({0,607                                                                                        2})})}),608 frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0,609                                                                                        2}),610                                                                             frozenset({0,611                                                                                        1,612                                                                                        2})}),613                                                                  frozenset({frozenset({0,614                                                                                        1}),615                                                                             frozenset({0,616                                                                                        1,617                                                                                        2})}),618                                                                  frozenset({frozenset({2}),619                                                                             frozenset({1,620                                                                                        2})}),621                                                                  frozenset({frozenset({1}),622                                                                             frozenset({1,623                                                                                        2})})})}"""624        cubo = test.test_set.linegraph(cube)625        self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt)626    def test_depth(self):627        nested_tuple = (1, (2, (3, (4, (5, 6)))))628        nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}629        nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]630        self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))631        self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))632        self.assertEqual(pprint.pformat(nested_list), repr(nested_list))633        lv1_tuple = '(1, (...))'634        lv1_dict = '{1: {...}}'635        lv1_list = '[1, [...]]'636        self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)637        self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)638        self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)639    def test_sort_unorderable_values(self):640        # Issue 3976:  sorted pprints fail for unorderable values.641        n = 20642        keys = [Unorderable() for i in range(n)]643        random.shuffle(keys)644        skeys = sorted(keys, key=id)645        clean = lambda s: s.replace(' ', '').replace('\n','')646        self.assertEqual(clean(pprint.pformat(set(keys))),647            '{' + ','.join(map(repr, skeys)) + '}')648        self.assertEqual(clean(pprint.pformat(frozenset(keys))),649            'frozenset({' + ','.join(map(repr, skeys)) + '})')650        self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),651            '{' + ','.join('%r:None' % k for k in skeys) + '}')652        # Issue 10017: TypeError on user-defined types as dict keys.653        self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),654                         '{1: 0, ' + repr(Unorderable) +': 0}')655        # Issue 14998: TypeError on tuples with NoneTypes as dict keys.656        keys = [(1,), (None,)]657        self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),658                         '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))659    def test_sort_orderable_and_unorderable_values(self):660        # Issue 22721:  sorted pprints is not stable661        a = Unorderable()662        b = Orderable(hash(a))  # should have the same hash value663        # self-test664        self.assertLess(a, b)665        self.assertLess(str(type(b)), str(type(a)))666        self.assertEqual(sorted([b, a]), [a, b])667        self.assertEqual(sorted([a, b]), [a, b])668        # set669        self.assertEqual(pprint.pformat(set([b, a]), width=1),670                         '{%r,\n %r}' % (a, b))671        self.assertEqual(pprint.pformat(set([a, b]), width=1),672                         '{%r,\n %r}' % (a, b))673        # dict674        self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1),675                         '{%r: None,\n %r: None}' % (a, b))676        self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1),677                         '{%r: None,\n %r: None}' % (a, b))678    def test_str_wrap(self):679        # pprint tries to wrap strings intelligently680        fox = 'the quick brown fox jumped over a lazy dog'681        self.assertEqual(pprint.pformat(fox, width=19), """\682('the quick brown '683 'fox jumped over '684 'a lazy dog')""")685        self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},686                                        width=25), """\687{'a': 1,688 'b': 'the quick brown '689      'fox jumped over '690      'a lazy dog',691 'c': 2}""")692        # With some special characters693        # - \n always triggers a new line in the pprint694        # - \t and \n are escaped695        # - non-ASCII is allowed696        # - an apostrophe doesn't disrupt the pprint697        special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"698        self.assertEqual(pprint.pformat(special, width=68), repr(special))699        self.assertEqual(pprint.pformat(special, width=31), """\700('Portons dix bons "whiskys"\\n'701 "à l'avocat goujat\\t qui "702 'fumait au zoo')""")703        self.assertEqual(pprint.pformat(special, width=20), """\704('Portons dix bons '705 '"whiskys"\\n'706 "à l'avocat "707 'goujat\\t qui '708 'fumait au zoo')""")709        self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\710[[[[['Portons dix bons "whiskys"\\n'711     "à l'avocat goujat\\t qui "712     'fumait au zoo']]]]]""")713        self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\714[[[[['Portons dix bons '715     '"whiskys"\\n'716     "à l'avocat "717     'goujat\\t qui '718     'fumait au zoo']]]]]""")719        self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\720[[[[['Portons dix '721     'bons "whiskys"\\n'722     "à l'avocat "723     'goujat\\t qui '724     'fumait au '725     'zoo']]]]]""")726        # An unwrappable string is formatted as its repr727        unwrappable = "x" * 100728        self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))729        self.assertEqual(pprint.pformat(''), "''")730        # Check that the pprint is a usable repr731        special *= 10732        for width in range(3, 40):733            formatted = pprint.pformat(special, width=width)734            self.assertEqual(eval(formatted), special)735            formatted = pprint.pformat([special] * 2, width=width)736            self.assertEqual(eval(formatted), [special] * 2)737    def test_compact(self):738        o = ([list(range(i * i)) for i in range(5)] +739             [list(range(i)) for i in range(6)])740        expected = """\741[[], [0], [0, 1, 2, 3],742 [0, 1, 2, 3, 4, 5, 6, 7, 8],743 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,744  14, 15],745 [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],746 [0, 1, 2, 3, 4]]"""747        self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)748    def test_compact_width(self):749        levels = 20750        number = 10751        o = [0] * number752        for i in range(levels - 1):753            o = [o]754        for w in range(levels * 2 + 1, levels + 3 * number - 1):755            lines = pprint.pformat(o, width=w, compact=True).splitlines()756            maxwidth = max(map(len, lines))757            self.assertLessEqual(maxwidth, w)758            self.assertGreater(maxwidth, w - 3)759    def test_bytes_wrap(self):760        self.assertEqual(pprint.pformat(b'', width=1), "b''")761        self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")762        letters = b'abcdefghijklmnopqrstuvwxyz'763        self.assertEqual(pprint.pformat(letters, width=29), repr(letters))764        self.assertEqual(pprint.pformat(letters, width=19), """\765(b'abcdefghijkl'766 b'mnopqrstuvwxyz')""")767        self.assertEqual(pprint.pformat(letters, width=18), """\768(b'abcdefghijkl'769 b'mnopqrstuvwx'770 b'yz')""")771        self.assertEqual(pprint.pformat(letters, width=16), """\772(b'abcdefghijkl'773 b'mnopqrstuvwx'774 b'yz')""")775        special = bytes(range(16))776        self.assertEqual(pprint.pformat(special, width=61), repr(special))777        self.assertEqual(pprint.pformat(special, width=48), """\778(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'779 b'\\x0c\\r\\x0e\\x0f')""")780        self.assertEqual(pprint.pformat(special, width=32), """\781(b'\\x00\\x01\\x02\\x03'782 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'783 b'\\x0c\\r\\x0e\\x0f')""")784        self.assertEqual(pprint.pformat(special, width=1), """\785(b'\\x00\\x01\\x02\\x03'786 b'\\x04\\x05\\x06\\x07'787 b'\\x08\\t\\n\\x0b'788 b'\\x0c\\r\\x0e\\x0f')""")789        self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},790                                        width=21), """\791{'a': 1,792 'b': b'abcdefghijkl'793      b'mnopqrstuvwx'794      b'yz',795 'c': 2}""")796        self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},797                                        width=20), """\798{'a': 1,799 'b': b'abcdefgh'800      b'ijklmnop'801      b'qrstuvwxyz',802 'c': 2}""")803        self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\804[[[[[[b'abcdefghijklmnop'805      b'qrstuvwxyz']]]]]]""")806        self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\807[[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'808      b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")809        # Check that the pprint is a usable repr810        for width in range(1, 64):811            formatted = pprint.pformat(special, width=width)812            self.assertEqual(eval(formatted), special)813            formatted = pprint.pformat([special] * 2, width=width)814            self.assertEqual(eval(formatted), [special] * 2)815    def test_bytearray_wrap(self):816        self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")817        letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')818        self.assertEqual(pprint.pformat(letters, width=40), repr(letters))819        self.assertEqual(pprint.pformat(letters, width=28), """\820bytearray(b'abcdefghijkl'821          b'mnopqrstuvwxyz')""")822        self.assertEqual(pprint.pformat(letters, width=27), """\823bytearray(b'abcdefghijkl'824          b'mnopqrstuvwx'825          b'yz')""")826        self.assertEqual(pprint.pformat(letters, width=25), """\827bytearray(b'abcdefghijkl'828          b'mnopqrstuvwx'829          b'yz')""")830        special = bytearray(range(16))831        self.assertEqual(pprint.pformat(special, width=72), repr(special))832        self.assertEqual(pprint.pformat(special, width=57), """\833bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'834          b'\\x0c\\r\\x0e\\x0f')""")835        self.assertEqual(pprint.pformat(special, width=41), """\836bytearray(b'\\x00\\x01\\x02\\x03'837          b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'838          b'\\x0c\\r\\x0e\\x0f')""")839        self.assertEqual(pprint.pformat(special, width=1), """\840bytearray(b'\\x00\\x01\\x02\\x03'841          b'\\x04\\x05\\x06\\x07'842          b'\\x08\\t\\n\\x0b'843          b'\\x0c\\r\\x0e\\x0f')""")844        self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},845                                        width=31), """\846{'a': 1,847 'b': bytearray(b'abcdefghijkl'848                b'mnopqrstuvwx'849                b'yz'),850 'c': 2}""")851        self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\852[[[[[bytearray(b'abcdefghijklmnop'853               b'qrstuvwxyz')]]]]]""")854        self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\855[[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'856               b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")857    def test_default_dict(self):858        d = collections.defaultdict(int)859        self.assertEqual(pprint.pformat(d, width=1), "defaultdict(<class 'int'>, {})")860        words = 'the quick brown fox jumped over a lazy dog'.split()861        d = collections.defaultdict(int, zip(words, itertools.count()))862        self.assertEqual(pprint.pformat(d),863"""\864defaultdict(<class 'int'>,865            {'a': 6,866             'brown': 2,867             'dog': 8,868             'fox': 3,869             'jumped': 4,870             'lazy': 7,871             'over': 5,872             'quick': 1,873             'the': 0})""")874    def test_counter(self):875        d = collections.Counter()876        self.assertEqual(pprint.pformat(d, width=1), "Counter()")877        d = collections.Counter('senselessness')878        self.assertEqual(pprint.pformat(d, width=40),879"""\880Counter({'s': 6,881         'e': 4,882         'n': 2,883         'l': 1})""")884    def test_chainmap(self):885        d = collections.ChainMap()886        self.assertEqual(pprint.pformat(d, width=1), "ChainMap({})")887        words = 'the quick brown fox jumped over a lazy dog'.split()888        items = list(zip(words, itertools.count()))889        d = collections.ChainMap(dict(items))890        self.assertEqual(pprint.pformat(d),891"""\892ChainMap({'a': 6,893          'brown': 2,894          'dog': 8,895          'fox': 3,896          'jumped': 4,897          'lazy': 7,898          'over': 5,899          'quick': 1,900          'the': 0})""")901        d = collections.ChainMap(dict(items), collections.OrderedDict(items))902        self.assertEqual(pprint.pformat(d),903"""\904ChainMap({'a': 6,905          'brown': 2,906          'dog': 8,907          'fox': 3,908          'jumped': 4,909          'lazy': 7,910          'over': 5,911          'quick': 1,912          'the': 0},913         OrderedDict([('the', 0),914                      ('quick', 1),915                      ('brown', 2),916                      ('fox', 3),917                      ('jumped', 4),918                      ('over', 5),919                      ('a', 6),920                      ('lazy', 7),921                      ('dog', 8)]))""")922    def test_deque(self):923        d = collections.deque()924        self.assertEqual(pprint.pformat(d, width=1), "deque([])")925        d = collections.deque(maxlen=7)926        self.assertEqual(pprint.pformat(d, width=1), "deque([], maxlen=7)")927        words = 'the quick brown fox jumped over a lazy dog'.split()928        d = collections.deque(zip(words, itertools.count()))929        self.assertEqual(pprint.pformat(d),930"""\931deque([('the', 0),932       ('quick', 1),933       ('brown', 2),934       ('fox', 3),935       ('jumped', 4),936       ('over', 5),937       ('a', 6),938       ('lazy', 7),939       ('dog', 8)])""")940        d = collections.deque(zip(words, itertools.count()), maxlen=7)941        self.assertEqual(pprint.pformat(d),942"""\943deque([('brown', 2),944       ('fox', 3),945       ('jumped', 4),946       ('over', 5),947       ('a', 6),948       ('lazy', 7),949       ('dog', 8)],950      maxlen=7)""")951    def test_user_dict(self):952        d = collections.UserDict()953        self.assertEqual(pprint.pformat(d, width=1), "{}")954        words = 'the quick brown fox jumped over a lazy dog'.split()955        d = collections.UserDict(zip(words, itertools.count()))956        self.assertEqual(pprint.pformat(d),957"""\958{'a': 6,959 'brown': 2,960 'dog': 8,961 'fox': 3,962 'jumped': 4,963 'lazy': 7,964 'over': 5,965 'quick': 1,966 'the': 0}""")967    def test_user_list(self):968        d = collections.UserList()969        self.assertEqual(pprint.pformat(d, width=1), "[]")970        words = 'the quick brown fox jumped over a lazy dog'.split()971        d = collections.UserList(zip(words, itertools.count()))972        self.assertEqual(pprint.pformat(d),973"""\974[('the', 0),975 ('quick', 1),976 ('brown', 2),977 ('fox', 3),978 ('jumped', 4),979 ('over', 5),980 ('a', 6),981 ('lazy', 7),982 ('dog', 8)]""")983    def test_user_string(self):984        d = collections.UserString('')985        self.assertEqual(pprint.pformat(d, width=1), "''")986        d = collections.UserString('the quick brown fox jumped over a lazy dog')987        self.assertEqual(pprint.pformat(d, width=20),988"""\989('the quick brown '990 'fox jumped over '991 'a lazy dog')""")992        self.assertEqual(pprint.pformat({1: d}, width=20),993"""\994{1: 'the quick '995    'brown fox '996    'jumped over a '997    'lazy dog'}""")998class DottedPrettyPrinter(pprint.PrettyPrinter):999    def format(self, object, context, maxlevels, level):1000        if isinstance(object, str):1001            if ' ' in object:1002                return repr(object), 1, 01003            else:1004                return object, 0, 01005        else:1006            return pprint.PrettyPrinter.format(1007                self, object, context, maxlevels, level)1008if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
