[2.7] closes bpo-31608: Fix a crash in methods of a subclass of _collections.deque with a bad __new__(). (GH-9179)

diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py
index c81064d..e6307ab 100644
--- a/Lib/test/test_deque.py
+++ b/Lib/test/test_deque.py
@@ -659,6 +659,21 @@
         d1 == d2   # not clear if this is supposed to be True or False,
                    # but it used to give a SystemError
 
+    @test_support.cpython_only
+    def test_bug_31608(self):
+        # The interpreter used to crash in specific cases where a deque
+        # subclass returned a non-deque.
+        class X(deque):
+            pass
+        d = X()
+        def bad___new__(cls, *args, **kwargs):
+            return [42]
+        X.__new__ = bad___new__
+        with self.assertRaises(TypeError):
+            d * 42  # shouldn't crash
+        with self.assertRaises(TypeError):
+            d + deque([1, 2, 3])  # shouldn't crash
+
 
 class SubclassWithKwargs(deque):
     def __init__(self, newarg=1):