Python mock.assert_called_with() Examples

The following are 30 code examples of mock.assert_called_with(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mock , or try the search function .
Example #1
Source File: mock.py    From odoo13-x64 with GNU General Public License v3.0 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            raise AssertionError('Expected call: %s\nNot called' % (expected,))

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '%s\n%s' % (msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #2
Source File: test_zdd.py    From marathon-lb with Apache License 2.0 6 votes vote down vote up
def test_scale_new_app_instances_to_target(self, mock):
        """When scaling new instances up, if we have met or surpassed the
           amount of instances deployed for old_app, go right to our
           deployment target amount of instances for new_app
        """
        def run(args):
            new_app = {
                'instances': 10,
                'labels': {
                    'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30
                }
            }
            old_app = {'instances': 8}
            args.initial_instances = 5
            zdd.scale_new_app_instances(args, new_app, old_app)
            mock.assert_called_with(
                args, new_app, 30)
        for a in _arg_cases():
            run(a) 
Example #3
Source File: mock.py    From odoo12-x64 with GNU General Public License v3.0 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            raise AssertionError('Expected call: %s\nNot called' % (expected,))

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '%s\n%s' % (msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #4
Source File: testmock.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_assert_called_with_method_spec(self):
        def _check(mock):
            mock(1, b=2, c=3)
            mock.assert_called_with(1, 2, 3)
            mock.assert_called_with(a=1, b=2, c=3)
            self.assertRaises(AssertionError, mock.assert_called_with,
                              1, b=3, c=2)

        mock = Mock(spec=Something().meth)
        _check(mock)
        mock = Mock(spec=Something.cmeth)
        _check(mock)
        mock = Mock(spec=Something().cmeth)
        _check(mock)
        mock = Mock(spec=Something.smeth)
        _check(mock)
        mock = Mock(spec=Something().smeth)
        _check(mock) 
Example #5
Source File: testmock.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_assert_called_with_function_spec(self):
        def f(a, b, c, d=None):
            pass

        mock = Mock(spec=f)

        mock(1, b=2, c=3)
        mock.assert_called_with(1, 2, 3)
        mock.assert_called_with(a=1, b=2, c=3)
        self.assertRaises(AssertionError, mock.assert_called_with,
                          1, b=3, c=2)
        # Expected call doesn't match the spec's signature
        with self.assertRaises(AssertionError) as cm:
            mock.assert_called_with(e=8)
        if hasattr(cm.exception, '__cause__'):
            self.assertIsInstance(cm.exception.__cause__, TypeError) 
Example #6
Source File: test_zdd.py    From marathon-lb with Apache License 2.0 6 votes vote down vote up
def test_scale_new_app_instances_up_50_percent(self, mock):
        """When scaling new_app instances, increase instances by 50% of
           existing instances if we have not yet met or surpassed the amount
           of instances deployed by old_app
        """
        def run(args):
            args.initial_instances = 5
            new_app = {
                'instances': 10,
                'labels': {
                    'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30
                }
            }
            old_app = {'instances': 30}
            zdd.scale_new_app_instances(args, new_app, old_app)
            mock.assert_called_with(
                args, new_app, 15)
        for a in _arg_cases():
            run(a) 
Example #7
Source File: test_zdd.py    From marathon-lb with Apache License 2.0 6 votes vote down vote up
def test_scale_new_app_instances_hybrid(self, mock):
        """When scaling new instances up, if we have met or surpassed the
           amount of instances deployed for old_app, go right to our
           deployment target amount of instances for new_app
        """
        def run(args):
            new_app = {
                'instances': 10,
                'labels': {
                    'HAPROXY_DEPLOYMENT_NEW_INSTANCES': 15,
                    'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30
                }
            }
            old_app = {'instances': 20}
            args.initial_instances = 5
            zdd.scale_new_app_instances(args, new_app, old_app)
            mock.assert_called_with(
                args, new_app, 15)
        for a in _arg_cases():
            run(a) 
Example #8
Source File: test_zdd.py    From marathon-lb with Apache License 2.0 6 votes vote down vote up
def test_pre_kill_hook(self, mock):
        # TODO(BM): This test is naive. An end-to-end test would be nice.
        def run(args):
            args.pre_kill_hook = 'myhook'
            old_app = {
                'id': 'oldApp'
            }
            new_app = {
                'id': 'newApp'
            }
            tasks_to_kill = ['task1', 'task2']
            zdd.execute_pre_kill_hook(args,
                                      old_app,
                                      tasks_to_kill,
                                      new_app)
            mock.assert_called_with([args.pre_kill_hook,
                                     '{"id": "oldApp"}',
                                     '["task1", "task2"]',
                                     '{"id": "newApp"}'])
        for a in _arg_cases():
            run(a) 
Example #9
Source File: test_proxy.py    From openstacksdk with Apache License 2.0 6 votes vote down vote up
def test__get_resource_from_id(self):
        id = "eye dee"
        value = "hello"
        attrs = {"first": "Brian", "last": "Curtin"}

        # The isinstance check needs to take a type, not an instance,
        # so the mock.assert_called_with method isn't helpful here since
        # we can't pass in a mocked object. This class is a crude version
        # of that same behavior to let us check that `new` gets
        # called with the expected arguments.

        class Fake:
            call = {}

            @classmethod
            def new(cls, **kwargs):
                cls.call = kwargs
                return value

        result = self.fake_proxy._get_resource(Fake, id, **attrs)

        self.assertDictEqual(
            dict(id=id, connection=mock.ANY, **attrs), Fake.call)
        self.assertEqual(value, result) 
Example #10
Source File: testmock.py    From keras-lambda with MIT License 6 votes vote down vote up
def test_assert_called_with_method_spec(self):
        def _check(mock):
            mock(1, b=2, c=3)
            mock.assert_called_with(1, 2, 3)
            mock.assert_called_with(a=1, b=2, c=3)
            self.assertRaises(AssertionError, mock.assert_called_with,
                              1, b=3, c=2)

        mock = Mock(spec=Something().meth)
        _check(mock)
        mock = Mock(spec=Something.cmeth)
        _check(mock)
        mock = Mock(spec=Something().cmeth)
        _check(mock)
        mock = Mock(spec=Something.smeth)
        _check(mock)
        mock = Mock(spec=Something().smeth)
        _check(mock) 
Example #11
Source File: mock.py    From keras-lambda with MIT License 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            raise AssertionError('Expected call: %s\nNot called' % (expected,))

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '%s\n%s' % (msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #12
Source File: mock.py    From rules_pip with MIT License 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                             % (expected, actual))
            raise AssertionError(error_message)

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '{}\n{}'.format(msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #13
Source File: mock.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                             % (expected, actual))
            raise AssertionError(error_message)

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '{}\n{}'.format(msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #14
Source File: mock.py    From ImageFusion with MIT License 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            raise AssertionError('Expected call: %s\nNot called' % (expected,))

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if not inPy3k and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '%s\n%s' % (msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #15
Source File: testmock.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_assert_called_with_function_spec(self):
        def f(a, b, c, d=None):
            pass

        mock = Mock(spec=f)

        mock(1, b=2, c=3)
        mock.assert_called_with(1, 2, 3)
        mock.assert_called_with(a=1, b=2, c=3)
        self.assertRaises(AssertionError, mock.assert_called_with,
                          1, b=3, c=2)
        # Expected call doesn't match the spec's signature
        with self.assertRaises(AssertionError) as cm:
            mock.assert_called_with(e=8)
        if hasattr(cm.exception, '__cause__'):
            self.assertIsInstance(cm.exception.__cause__, TypeError) 
Example #16
Source File: testmock.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_assert_called_with_method_spec(self):
        def _check(mock):
            mock(1, b=2, c=3)
            mock.assert_called_with(1, 2, 3)
            mock.assert_called_with(a=1, b=2, c=3)
            self.assertRaises(AssertionError, mock.assert_called_with,
                              1, b=3, c=2)

        mock = Mock(spec=Something().meth)
        _check(mock)
        mock = Mock(spec=Something.cmeth)
        _check(mock)
        mock = Mock(spec=Something().cmeth)
        _check(mock)
        mock = Mock(spec=Something.smeth)
        _check(mock)
        mock = Mock(spec=Something().smeth)
        _check(mock) 
Example #17
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 6 votes vote down vote up
def test_assert_called_with_method_spec(self):
        def _check(mock):
            mock(1, b=2, c=3)
            mock.assert_called_with(1, 2, 3)
            mock.assert_called_with(a=1, b=2, c=3)
            self.assertRaises(AssertionError, mock.assert_called_with,
                              1, b=3, c=2)

        mock = Mock(spec=Something().meth)
        _check(mock)
        mock = Mock(spec=Something.cmeth)
        _check(mock)
        mock = Mock(spec=Something().cmeth)
        _check(mock)
        mock = Mock(spec=Something.smeth)
        _check(mock)
        mock = Mock(spec=Something().smeth)
        _check(mock) 
Example #18
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 6 votes vote down vote up
def test_assert_called_with_function_spec(self):
        def f(a, b, c, d=None):
            pass

        mock = Mock(spec=f)

        mock(1, b=2, c=3)
        mock.assert_called_with(1, 2, 3)
        mock.assert_called_with(a=1, b=2, c=3)
        self.assertRaises(AssertionError, mock.assert_called_with,
                          1, b=3, c=2)
        # Expected call doesn't match the spec's signature
        with self.assertRaises(AssertionError) as cm:
            mock.assert_called_with(e=8)
        if hasattr(cm.exception, '__cause__'):
            self.assertIsInstance(cm.exception.__cause__, TypeError) 
Example #19
Source File: testmock.py    From keras-lambda with MIT License 6 votes vote down vote up
def test_assert_called_with_function_spec(self):
        def f(a, b, c, d=None):
            pass

        mock = Mock(spec=f)

        mock(1, b=2, c=3)
        mock.assert_called_with(1, 2, 3)
        mock.assert_called_with(a=1, b=2, c=3)
        self.assertRaises(AssertionError, mock.assert_called_with,
                          1, b=3, c=2)
        # Expected call doesn't match the spec's signature
        with self.assertRaises(AssertionError) as cm:
            mock.assert_called_with(e=8)
        if hasattr(cm.exception, '__cause__'):
            self.assertIsInstance(cm.exception.__cause__, TypeError) 
Example #20
Source File: mock.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            raise AssertionError('Expected call: %s\nNot called' % (expected,))

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '%s\n%s' % (msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause) 
Example #21
Source File: testmock.py    From odoo12-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_assert_called_with(self):
        mock = Mock()
        mock()

        # Will raise an exception if it fails
        mock.assert_called_with()
        self.assertRaises(AssertionError, mock.assert_called_with, 1)

        mock.reset_mock()
        self.assertRaises(AssertionError, mock.assert_called_with)

        mock(1, 2, 3, a='fish', b='nothing')
        mock.assert_called_with(1, 2, 3, a='fish', b='nothing') 
Example #22
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_assert_called_with(self):
        mock = Mock()
        mock()

        # Will raise an exception if it fails
        mock.assert_called_with()
        self.assertRaises(AssertionError, mock.assert_called_with, 1)

        mock.reset_mock()
        self.assertRaises(AssertionError, mock.assert_called_with)

        mock(1, 2, 3, a='fish', b='nothing')
        mock.assert_called_with(1, 2, 3, a='fish', b='nothing') 
Example #23
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_side_effect(self):
        mock = Mock()

        def effect(*args, **kwargs):
            raise SystemError('kablooie')

        mock.side_effect = effect
        self.assertRaises(SystemError, mock, 1, 2, fish=3)
        mock.assert_called_with(1, 2, fish=3)

        results = [1, 2, 3]
        def effect():
            return results.pop()
        mock.side_effect = effect

        self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
                          "side effect not used correctly")

        mock = Mock(side_effect=sentinel.SideEffect)
        self.assertEqual(mock.side_effect, sentinel.SideEffect,
                          "side effect in constructor not used")

        def side_effect():
            return DEFAULT
        mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
        self.assertEqual(mock(), sentinel.RETURN) 
Example #24
Source File: mock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def assert_any_call(self, *args, **kwargs):
        """assert the mock has been called with the specified arguments.

        The assert passes if the mock has *ever* been called, unlike
        `assert_called_with` and `assert_called_once_with` that only pass if
        the call is the most recent one."""
        expected = self._call_matcher((args, kwargs))
        actual = [self._call_matcher(c) for c in self.call_args_list]
        if expected not in actual:
            cause = expected if isinstance(expected, Exception) else None
            expected_string = self._format_mock_call_signature(args, kwargs)
            six.raise_from(AssertionError(
                '%s call not found' % expected_string
            ), cause) 
Example #25
Source File: mock.py    From odoo12-x64 with GNU General Public License v3.0 5 votes vote down vote up
def assert_any_call(self, *args, **kwargs):
        """assert the mock has been called with the specified arguments.

        The assert passes if the mock has *ever* been called, unlike
        `assert_called_with` and `assert_called_once_with` that only pass if
        the call is the most recent one."""
        expected = self._call_matcher((args, kwargs))
        actual = [self._call_matcher(c) for c in self.call_args_list]
        if expected not in actual:
            cause = expected if isinstance(expected, Exception) else None
            expected_string = self._format_mock_call_signature(args, kwargs)
            six.raise_from(AssertionError(
                '%s call not found' % expected_string
            ), cause) 
Example #26
Source File: mock.py    From odoo12-x64 with GNU General Public License v3.0 5 votes vote down vote up
def assert_called_once_with(_mock_self, *args, **kwargs):
        """assert that the mock was called exactly once and with the specified
        arguments."""
        self = _mock_self
        if not self.call_count == 1:
            msg = ("Expected '%s' to be called once. Called %s times." %
                   (self._mock_name or 'mock', self.call_count))
            raise AssertionError(msg)
        return self.assert_called_with(*args, **kwargs) 
Example #27
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_wraps_attributes(self):
        class Real(object):
            attribute = Mock()

        real = Real()

        mock = Mock(wraps=real)
        self.assertEqual(mock.attribute(), real.attribute())
        self.assertRaises(AttributeError, lambda: mock.fish)

        self.assertNotEqual(mock.attribute, real.attribute)
        result = mock.attribute.frog(1, 2, fish=3)
        Real.attribute.frog.assert_called_with(1, 2, fish=3)
        self.assertEqual(result, Real.attribute.frog()) 
Example #28
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_spec_list_subclass(self):
        class Sub(list):
            pass
        mock = Mock(spec=Sub(['foo']))

        mock.append(3)
        mock.append.assert_called_with(3)
        self.assertRaises(AttributeError, getattr, mock, 'foo') 
Example #29
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_setting_call(self):
        mock = Mock()
        def __call__(self, a):
            return self._mock_call(a)

        type(mock).__call__ = __call__
        mock('one')
        mock.assert_called_with('one')

        self.assertRaises(TypeError, mock, 'one', 'two') 
Example #30
Source File: testmock.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def test_wraps_calls(self):
        real = Mock()

        mock = Mock(wraps=real)
        self.assertEqual(mock(), real())

        real.reset_mock()

        mock(1, 2, fish=3)
        real.assert_called_with(1, 2, fish=3)