]> granicus.if.org Git - python/commitdiff
Issue 20968. unittest.mock.MagicMock now supports division
authorMichael Foord <michael@voidspace.org.uk>
Mon, 14 Apr 2014 15:23:48 +0000 (11:23 -0400)
committerMichael Foord <michael@voidspace.org.uk>
Mon, 14 Apr 2014 15:23:48 +0000 (11:23 -0400)
Lib/unittest/mock.py
Lib/unittest/test/testmock/testmagicmethods.py
Misc/NEWS

index 8b765034293afc544df20869bec9c8e942f40bc1..a23df5a73dd272777f2a572c953a102abfc83adf 100644 (file)
@@ -1634,7 +1634,9 @@ magic_methods = (
     "bool next "
 )
 
-numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
+numerics = (
+    "add sub mul div floordiv mod lshift rshift and xor or pow truediv"
+)
 inplace = ' '.join('i%s' % n for n in numerics.split())
 right = ' '.join('r%s' % n for n in numerics.split())
 
index 5ff158dd12a30ad8bec91a323d4cfab204bfee5b..cc0e707ece656282ba8373eae3f4fa6bf8842e85 100644 (file)
@@ -126,6 +126,31 @@ class TestMockingMagicMethods(unittest.TestCase):
         self.assertEqual(7 + mock, mock)
         self.assertEqual(mock.value, 16)
 
+    def test_division(self):
+        original = mock = Mock()
+        mock.value = 32
+        self.assertRaises(TypeError, lambda: mock / 2)
+
+        def truediv(self, other):
+            mock.value /= other
+            return self
+        mock.__truediv__ = truediv
+        self.assertEqual(mock / 2, mock)
+        self.assertEqual(mock.value, 16)
+
+        del mock.__truediv__
+        def itruediv(mock):
+            mock /= 4
+        self.assertRaises(TypeError, itruediv, mock)
+        mock.__itruediv__ = truediv
+        mock /= 8
+        self.assertEqual(mock, original)
+        self.assertEqual(mock.value, 2)
+
+        self.assertRaises(TypeError, lambda: 8 / mock)
+        mock.__rtruediv__ = truediv
+        self.assertEqual(0.5 / mock, mock)
+        self.assertEqual(mock.value, 4)
 
     def test_hash(self):
         mock = Mock()
index 6e149686294e70f910cc3774bf30b486e50906e3..5bab4932aff6bf024344063506e9fe57a1947cb8 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -30,6 +30,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #20968: unittest.mock.MagicMock now supports division.
+  Patch by Johannes Baiter.
+
 - Fix arbitrary memory access in JSONDecoder.raw_decode with a negative second
   parameter. Bug reported by Guido Vranken.