[2.7] bpo-32137: The repr of deeply nested dict now raises a RuntimeError (GH-4570) (#5493)

instead of crashing due to a stack overflow.

This perhaps will fix similar problems in other extension types.
(cherry picked from commit 1fb72d2ad243c965d4432b4e93884064001a2607)
diff --git a/Lib/test/list_tests.py b/Lib/test/list_tests.py
index ed606db..54cfb97 100644
--- a/Lib/test/list_tests.py
+++ b/Lib/test/list_tests.py
@@ -45,10 +45,11 @@
         self.assertEqual(str(a2), "[0, 1, 2, [...], 3]")
         self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
 
-        l0 = []
-        for i in xrange(sys.getrecursionlimit() + 100):
-            l0 = [l0]
-        self.assertRaises(RuntimeError, repr, l0)
+    def test_repr_deep(self):
+        a = self.type2test([])
+        for i in range(sys.getrecursionlimit() + 100):
+            a = self.type2test([a])
+        self.assertRaises(RuntimeError, repr, a)
 
     def test_print(self):
         d = self.type2test(xrange(200))
diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py
index f43750b..248dee2 100644
--- a/Lib/test/mapping_tests.py
+++ b/Lib/test/mapping_tests.py
@@ -2,6 +2,7 @@
 import unittest
 import UserDict
 import test_support
+import sys
 
 
 class BasicTestMappingProtocol(unittest.TestCase):
@@ -645,6 +646,14 @@
         d = self._full_mapping({1: BadRepr()})
         self.assertRaises(Exc, repr, d)
 
+    def test_repr_deep(self):
+        d = self._empty_mapping()
+        for i in range(sys.getrecursionlimit() + 100):
+            d0 = d
+            d = self._empty_mapping()
+            d[1] = d0
+        self.assertRaises(RuntimeError, repr, d)
+
     def test_le(self):
         self.assertTrue(not (self._empty_mapping() < self._empty_mapping()))
         self.assertTrue(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L})))
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 6b2db34..aacd473 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -3,6 +3,7 @@
 
 import UserDict, random, string
 import gc, weakref
+import sys
 
 
 class DictTest(unittest.TestCase):
@@ -422,6 +423,12 @@
         d = {1: BadRepr()}
         self.assertRaises(Exc, repr, d)
 
+    def test_repr_deep(self):
+        d = {}
+        for i in range(sys.getrecursionlimit() + 100):
+            d = {1: d}
+        self.assertRaises(RuntimeError, repr, d)
+
     def test_le(self):
         self.assertFalse({} < {})
         self.assertFalse({1: 2} < {1L: 2L})