summaryrefslogtreecommitdiff
path: root/Lib/unittest
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2017-01-21 23:15:18 +0200
committerSerhiy Storchaka <storchaka@gmail.com>2017-01-21 23:15:18 +0200
commit3e7b1a2c51b76bc686d3a358299c51ffc0f17d89 (patch)
tree4b42a127e07ed1ff60ef69ede8130f476739bdf2 /Lib/unittest
parenta026f73c75337c598600c9057163ddb2f83cf872 (diff)
parent011a2f3455eae95971ac714907815ff6c6818456 (diff)
downloadcpython-3e7b1a2c51b76bc686d3a358299c51ffc0f17d89.tar.gz
Issue #28735: Fixed the comparison of mock.MagickMock with mock.ANY.
Diffstat (limited to 'Lib/unittest')
-rw-r--r--Lib/unittest/mock.py51
-rw-r--r--Lib/unittest/runner.py2
-rw-r--r--Lib/unittest/test/test_assertions.py18
-rw-r--r--Lib/unittest/test/test_loader.py8
-rw-r--r--Lib/unittest/test/testmock/support.py2
-rw-r--r--Lib/unittest/test/testmock/testhelpers.py14
-rw-r--r--Lib/unittest/test/testmock/testmagicmethods.py1
-rw-r--r--Lib/unittest/test/testmock/testmock.py39
-rw-r--r--Lib/unittest/test/testmock/testpatch.py10
9 files changed, 110 insertions, 35 deletions
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 0512cca4e2..b6b3836234 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -60,18 +60,6 @@ def _is_exception(obj):
)
-class _slotted(object):
- __slots__ = ['a']
-
-
-# Do not use this tuple. It was never documented as a public API.
-# It will be removed. It has no obvious signs of users on github.
-DescriptorTypes = (
- type(_slotted.a),
- property,
-)
-
-
def _get_signature_object(func, as_instance, eat_self):
"""
Given an arbitrary, possibly callable object, try to create a suitable
@@ -205,6 +193,12 @@ def _setup_func(funcopy, mock):
def assert_called_with(*args, **kwargs):
return mock.assert_called_with(*args, **kwargs)
+ def assert_called(*args, **kwargs):
+ return mock.assert_called(*args, **kwargs)
+ def assert_not_called(*args, **kwargs):
+ return mock.assert_not_called(*args, **kwargs)
+ def assert_called_once(*args, **kwargs):
+ return mock.assert_called_once(*args, **kwargs)
def assert_called_once_with(*args, **kwargs):
return mock.assert_called_once_with(*args, **kwargs)
def assert_has_calls(*args, **kwargs):
@@ -235,6 +229,9 @@ def _setup_func(funcopy, mock):
funcopy.assert_has_calls = assert_has_calls
funcopy.assert_any_call = assert_any_call
funcopy.reset_mock = reset_mock
+ funcopy.assert_called = assert_called
+ funcopy.assert_not_called = assert_not_called
+ funcopy.assert_called_once = assert_called_once
mock._mock_delegate = funcopy
@@ -525,7 +522,7 @@ class NonCallableMock(Base):
side_effect = property(__get_side_effect, __set_side_effect)
- def reset_mock(self, visited=None):
+ def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
"Restore the mock object to its initial state."
if visited is None:
visited = []
@@ -540,6 +537,11 @@ class NonCallableMock(Base):
self.call_args_list = _CallList()
self.method_calls = _CallList()
+ if return_value:
+ self._mock_return_value = DEFAULT
+ if side_effect:
+ self._mock_side_effect = None
+
for child in self._mock_children.values():
if isinstance(child, _SpecState):
continue
@@ -774,6 +776,24 @@ class NonCallableMock(Base):
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg)
+ def assert_called(_mock_self):
+ """assert that the mock was called at least once
+ """
+ self = _mock_self
+ if self.call_count == 0:
+ msg = ("Expected '%s' to have been called." %
+ self._mock_name or 'mock')
+ raise AssertionError(msg)
+
+ def assert_called_once(_mock_self):
+ """assert that the mock was called only once.
+ """
+ self = _mock_self
+ if not self.call_count == 1:
+ msg = ("Expected '%s' to have been called once. Called %s times." %
+ (self._mock_name or 'mock', self.call_count))
+ raise AssertionError(msg)
+
def assert_called_with(_mock_self, *args, **kwargs):
"""assert that the mock was called with the specified arguments.
@@ -822,7 +842,7 @@ class NonCallableMock(Base):
if expected not in all_calls:
raise AssertionError(
'Calls not found.\nExpected: %r\n'
- 'Actual: %r' % (calls, self.mock_calls)
+ 'Actual: %r' % (_CallList(calls), self.mock_calls)
) from cause
return
@@ -1945,9 +1965,8 @@ class _Call(tuple):
If the _Call has no name then it will match any name.
"""
- def __new__(cls, value=(), name=None, parent=None, two=False,
+ def __new__(cls, value=(), name='', parent=None, two=False,
from_kall=True):
- name = ''
args = ()
kwargs = {}
_len = len(value)
diff --git a/Lib/unittest/runner.py b/Lib/unittest/runner.py
index 2112262e4e..2c5ea4ab07 100644
--- a/Lib/unittest/runner.py
+++ b/Lib/unittest/runner.py
@@ -167,7 +167,7 @@ class TextTestRunner(object):
if self.warnings in ['default', 'always']:
warnings.filterwarnings('module',
category=DeprecationWarning,
- message='Please use assert\w+ instead.')
+ message=r'Please use assert\w+ instead.')
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
diff --git a/Lib/unittest/test/test_assertions.py b/Lib/unittest/test/test_assertions.py
index e6e2bc2ca7..1b0e83312d 100644
--- a/Lib/unittest/test/test_assertions.py
+++ b/Lib/unittest/test/test_assertions.py
@@ -240,7 +240,7 @@ class TestLongMessage(unittest.TestCase):
# Error messages are multiline so not testing on full message
# assertTupleEqual and assertListEqual delegate to this method
self.assertMessages('assertSequenceEqual', ([], [None]),
- ["\+ \[None\]$", "^oops$", r"\+ \[None\]$",
+ [r"\+ \[None\]$", "^oops$", r"\+ \[None\]$",
r"\+ \[None\] : oops$"])
def testAssertSetEqual(self):
@@ -250,21 +250,21 @@ class TestLongMessage(unittest.TestCase):
def testAssertIn(self):
self.assertMessages('assertIn', (None, []),
- ['^None not found in \[\]$', "^oops$",
- '^None not found in \[\]$',
- '^None not found in \[\] : oops$'])
+ [r'^None not found in \[\]$', "^oops$",
+ r'^None not found in \[\]$',
+ r'^None not found in \[\] : oops$'])
def testAssertNotIn(self):
self.assertMessages('assertNotIn', (None, [None]),
- ['^None unexpectedly found in \[None\]$', "^oops$",
- '^None unexpectedly found in \[None\]$',
- '^None unexpectedly found in \[None\] : oops$'])
+ [r'^None unexpectedly found in \[None\]$', "^oops$",
+ r'^None unexpectedly found in \[None\]$',
+ r'^None unexpectedly found in \[None\] : oops$'])
def testAssertDictEqual(self):
self.assertMessages('assertDictEqual', ({}, {'key': 'value'}),
[r"\+ \{'key': 'value'\}$", "^oops$",
- "\+ \{'key': 'value'\}$",
- "\+ \{'key': 'value'\} : oops$"])
+ r"\+ \{'key': 'value'\}$",
+ r"\+ \{'key': 'value'\} : oops$"])
def testAssertDictContainsSubset(self):
with warnings.catch_warnings():
diff --git a/Lib/unittest/test/test_loader.py b/Lib/unittest/test/test_loader.py
index 31e2f0fc3d..1131a755ea 100644
--- a/Lib/unittest/test/test_loader.py
+++ b/Lib/unittest/test/test_loader.py
@@ -390,7 +390,7 @@ class Test_TestLoader(unittest.TestCase):
suite = loader.loadTestsFromName('abc () //')
error, test = self.check_deferred_error(loader, suite)
expected = "Failed to import test module: abc () //"
- expected_regex = "Failed to import test module: abc \(\) //"
+ expected_regex = r"Failed to import test module: abc \(\) //"
self.assertIn(
expected, error,
'missing error string in %r' % error)
@@ -502,7 +502,7 @@ class Test_TestLoader(unittest.TestCase):
suite = loader.loadTestsFromName('abc () //', unittest)
error, test = self.check_deferred_error(loader, suite)
expected = "module 'unittest' has no attribute 'abc () //'"
- expected_regex = "module 'unittest' has no attribute 'abc \(\) //'"
+ expected_regex = r"module 'unittest' has no attribute 'abc \(\) //'"
self.assertIn(
expected, error,
'missing error string in %r' % error)
@@ -809,7 +809,7 @@ class Test_TestLoader(unittest.TestCase):
suite = loader.loadTestsFromNames(['abc () //'])
error, test = self.check_deferred_error(loader, list(suite)[0])
expected = "Failed to import test module: abc () //"
- expected_regex = "Failed to import test module: abc \(\) //"
+ expected_regex = r"Failed to import test module: abc \(\) //"
self.assertIn(
expected, error,
'missing error string in %r' % error)
@@ -928,7 +928,7 @@ class Test_TestLoader(unittest.TestCase):
suite = loader.loadTestsFromNames(['abc () //'], unittest)
error, test = self.check_deferred_error(loader, list(suite)[0])
expected = "module 'unittest' has no attribute 'abc () //'"
- expected_regex = "module 'unittest' has no attribute 'abc \(\) //'"
+ expected_regex = r"module 'unittest' has no attribute 'abc \(\) //'"
self.assertIn(
expected, error,
'missing error string in %r' % error)
diff --git a/Lib/unittest/test/testmock/support.py b/Lib/unittest/test/testmock/support.py
index f4738793b3..205431adca 100644
--- a/Lib/unittest/test/testmock/support.py
+++ b/Lib/unittest/test/testmock/support.py
@@ -1,5 +1,3 @@
-import sys
-
def is_instance(obj, klass):
"""Version of is_instance that doesn't access __class__"""
return issubclass(type(obj), klass)
diff --git a/Lib/unittest/test/testmock/testhelpers.py b/Lib/unittest/test/testmock/testhelpers.py
index 34776347da..d5f9e7c1d6 100644
--- a/Lib/unittest/test/testmock/testhelpers.py
+++ b/Lib/unittest/test/testmock/testhelpers.py
@@ -306,6 +306,20 @@ class CallTest(unittest.TestCase):
other_args = _Call(((1, 2), {'a': 3}))
self.assertEqual(args, other_args)
+ def test_call_with_name(self):
+ self.assertEqual(
+ 'foo',
+ _Call((), 'foo')[0],
+ )
+ self.assertEqual(
+ '',
+ _Call((('bar', 'barz'), ), )[0]
+ )
+ self.assertEqual(
+ '',
+ _Call((('bar', 'barz'), {'hello': 'world'}), )[0]
+ )
+
class SpecSignatureTest(unittest.TestCase):
diff --git a/Lib/unittest/test/testmock/testmagicmethods.py b/Lib/unittest/test/testmock/testmagicmethods.py
index bb9b956bb2..24569b532d 100644
--- a/Lib/unittest/test/testmock/testmagicmethods.py
+++ b/Lib/unittest/test/testmock/testmagicmethods.py
@@ -1,5 +1,4 @@
import unittest
-import inspect
import sys
from unittest.mock import Mock, MagicMock, _magics
diff --git a/Lib/unittest/test/testmock/testmock.py b/Lib/unittest/test/testmock/testmock.py
index a96ec683a9..b64c8663d2 100644
--- a/Lib/unittest/test/testmock/testmock.py
+++ b/Lib/unittest/test/testmock/testmock.py
@@ -1250,6 +1250,27 @@ class MockTest(unittest.TestCase):
with self.assertRaises(AssertionError):
m.hello.assert_not_called()
+ def test_assert_called(self):
+ m = Mock()
+ with self.assertRaises(AssertionError):
+ m.hello.assert_called()
+ m.hello()
+ m.hello.assert_called()
+
+ m.hello()
+ m.hello.assert_called()
+
+ def test_assert_called_once(self):
+ m = Mock()
+ with self.assertRaises(AssertionError):
+ m.hello.assert_called_once()
+ m.hello()
+ m.hello.assert_called_once()
+
+ m.hello()
+ with self.assertRaises(AssertionError):
+ m.hello.assert_called_once()
+
#Issue21256 printout of keyword args should be in deterministic order
def test_sorted_call_signature(self):
m = Mock()
@@ -1267,6 +1288,24 @@ class MockTest(unittest.TestCase):
self.assertEqual(m.method_calls[0], c)
self.assertEqual(m.method_calls[1], i)
+ def test_reset_return_sideeffect(self):
+ m = Mock(return_value=10, side_effect=[2,3])
+ m.reset_mock(return_value=True, side_effect=True)
+ self.assertIsInstance(m.return_value, Mock)
+ self.assertEqual(m.side_effect, None)
+
+ def test_reset_return(self):
+ m = Mock(return_value=10, side_effect=[2,3])
+ m.reset_mock(return_value=True)
+ self.assertIsInstance(m.return_value, Mock)
+ self.assertNotEqual(m.side_effect, None)
+
+ def test_reset_sideeffect(self):
+ m = Mock(return_value=10, side_effect=[2,3])
+ m.reset_mock(side_effect=True)
+ self.assertEqual(m.return_value, 10)
+ self.assertEqual(m.side_effect, None)
+
def test_mock_add_spec(self):
class _One(object):
one = 1
diff --git a/Lib/unittest/test/testmock/testpatch.py b/Lib/unittest/test/testmock/testpatch.py
index dfce3696d6..fe4ecefd44 100644
--- a/Lib/unittest/test/testmock/testpatch.py
+++ b/Lib/unittest/test/testmock/testpatch.py
@@ -10,9 +10,9 @@ from unittest.test.testmock import support
from unittest.test.testmock.support import SomeClass, is_instance
from unittest.mock import (
- NonCallableMock, CallableMixin, patch, sentinel,
+ NonCallableMock, CallableMixin, sentinel,
MagicMock, Mock, NonCallableMagicMock, patch, _patch,
- DEFAULT, call, _get_target, _patch
+ DEFAULT, call, _get_target
)
@@ -969,8 +969,14 @@ class PatchTest(unittest.TestCase):
def test_autospec_function(self):
@patch('%s.function' % __name__, autospec=True)
def test(mock):
+ function.assert_not_called()
+ self.assertRaises(AssertionError, function.assert_called)
+ self.assertRaises(AssertionError, function.assert_called_once)
function(1)
+ self.assertRaises(AssertionError, function.assert_not_called)
function.assert_called_with(1)
+ function.assert_called()
+ function.assert_called_once()
function(2, 3)
function.assert_called_with(2, 3)