Python unittest.mock.return_value() Examples

The following are 30 code examples of unittest.mock.return_value(). 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 unittest.mock , or try the search function .
Example #1
Source File: testmock.py    From jawfish with MIT License 7 votes vote down vote up
def test_configure_mock(self):
        mock = Mock(foo='bar')
        self.assertEqual(mock.foo, 'bar')

        mock = MagicMock(foo='bar')
        self.assertEqual(mock.foo, 'bar')

        kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
                  'foo': MagicMock()}
        mock = Mock(**kwargs)
        self.assertRaises(KeyError, mock)
        self.assertEqual(mock.foo.bar(), 33)
        self.assertIsInstance(mock.foo, MagicMock)

        mock = Mock()
        mock.configure_mock(**kwargs)
        self.assertRaises(KeyError, mock)
        self.assertEqual(mock.foo.bar(), 33)
        self.assertIsInstance(mock.foo, MagicMock) 
Example #2
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_sh_on_change(session_handler, monkeypatch, session_store):
    """
    unit tested:  on_change

    test case:
    passthrough call to session_store.update
    """
    sh = session_handler
    monkeypatch.setattr(sh, 'session_store', session_store)
    with mock.patch.object(sh.session_store, 'update') as ss_up:
        ss_up.return_value = None

        sh.on_change('session')

        ss_up.assert_called_once_with('session')


# ------------------------------------------------------------------------------
# NativeSessionManager
# ------------------------------------------------------------------------------ 
Example #3
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_sh_dogetsession_notouch(session_handler, monkeypatch, session_key):
    """
    unit tested: do_get_session

    test case:
    - retrieve_session returns a session
    - validate will be called
    - auto_touch is False by default, so skipping its clode block
    - session is returned
    """
    sh = session_handler

    monkeypatch.setattr(sh, '_retrieve_session', lambda x: 'session')

    with mock.patch.object(NativeSessionHandler, 'validate') as sh_validate:
        sh_validate.return_value = None

        result = sh.do_get_session(session_key)
        sh_validate.assert_called_once_with('session', session_key)
        assert result == 'session' 
Example #4
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_nsm_remove_attribute_nothing(
        default_native_session_manager, monkeypatch, mock_session):
    """
    unit tested:  remove_attribute

    test case:
    removing an attribute that doesn't exist returns None
    """
    nsm = default_native_session_manager
    mock_session.remove_attribute.return_value = None
    monkeypatch.setattr(nsm, '_lookup_required_session', lambda x: mock_session)
    with mock.patch.object(nsm.session_handler, 'on_change') as mocky:
        mocky.return_value = None

        result = nsm.remove_attribute('sessionkey123',
                                      attribute_key='attr321')

        assert result is None 
Example #5
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_nsm_remove_attribute(
        default_native_session_manager, monkeypatch, mock_session):
    """
    unit tested:  remove_attribute

    test case:
    successfully removes an attribute
    """
    nsm = default_native_session_manager
    monkeypatch.setattr(mock_session, 'remove_attribute', lambda x: 'attr1')
    monkeypatch.setattr(nsm, '_lookup_required_session', lambda x: mock_session)
    with mock.patch.object(nsm.session_handler, 'on_change') as mocky:
        mocky.return_value = None

        result = nsm.remove_attribute('sessionkey123',
                                      attribute_key='attr321')

        mocky.assert_called_once_with(mock_session)
        assert result == 'attr1' 
Example #6
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_nsm_set_attribute(
        default_native_session_manager, monkeypatch, mock_session):
    """
    unit tested:  set_attribute

    test case:
    sets an attribute
    """
    nsm = default_native_session_manager
    monkeypatch.setattr(nsm, '_lookup_required_session', lambda x: mock_session)
    with mock.patch.object(nsm.session_handler, 'on_change') as mocky:
        mocky.return_value = None
        with mock.patch.object(mock_session, 'set_attribute') as sia:
            sia.return_value = None

            nsm.set_attribute('sessionkey123',
                              attribute_key='attr321', value=321)

            sia.assert_called_once_with('attr321', 321)
            mocky.assert_called_once_with(mock_session) 
Example #7
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_nsm_remove_internal_attribute(
        default_native_session_manager, monkeypatch, mock_session):
    """
    unit tested:  remove_internal_attribute

    test case:
    successfully removes an internal_attribute
    """
    nsm = default_native_session_manager
    monkeypatch.setattr(mock_session, 'remove_internal_attribute', lambda x: 'attr1')
    monkeypatch.setattr(nsm, '_lookup_required_session', lambda x: mock_session)
    with mock.patch.object(nsm.session_handler, 'on_change') as mocky:
        mocky.return_value = None

        result = nsm.remove_internal_attribute('sessionkey123',
                                               attribute_key='attr321')

        mocky.assert_called_once_with(mock_session)
        assert result == 'attr1' 
Example #8
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_nsm_set_internal_attribute(
        default_native_session_manager, monkeypatch, mock_session):
    """
    unit tested:  set_internal_attribute

    test case:
    sets an internal_attribute
    """
    nsm = default_native_session_manager
    monkeypatch.setattr(nsm, '_lookup_required_session', lambda x: mock_session)
    with mock.patch.object(nsm.session_handler, 'on_change') as mocky:
        mocky.return_value = None
        with mock.patch.object(mock_session, 'set_internal_attribute') as sia:
            sia.return_value = None

            nsm.set_internal_attribute('sessionkey123',
                                       attribute_key='attr321', value=321)

            sia.assert_called_once_with('attr321', 321)
            mocky.assert_called_once_with(mock_session) 
Example #9
Source File: testmock.py    From Imogen with MIT License 6 votes vote down vote up
def test_configure_mock(self):
        mock = Mock(foo='bar')
        self.assertEqual(mock.foo, 'bar')

        mock = MagicMock(foo='bar')
        self.assertEqual(mock.foo, 'bar')

        kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
                  'foo': MagicMock()}
        mock = Mock(**kwargs)
        self.assertRaises(KeyError, mock)
        self.assertEqual(mock.foo.bar(), 33)
        self.assertIsInstance(mock.foo, MagicMock)

        mock = Mock()
        mock.configure_mock(**kwargs)
        self.assertRaises(KeyError, mock)
        self.assertEqual(mock.foo.bar(), 33)
        self.assertIsInstance(mock.foo, MagicMock) 
Example #10
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_nsm_set_absolute_timeout(
        default_native_session_manager, monkeypatch, mock_session):
    """
    unit tested: set_absolute_timeout

    test case:
    basic code exercise, passes through and returns
    """
    nsm = default_native_session_manager

    monkeypatch.setattr(nsm, '_lookup_required_session', lambda x: mock_session)

    with mock.patch.object(nsm.session_handler, 'on_change') as mocky:
        mocky.return_value = None
        nsm.set_absolute_timeout('sessionkey123', 'timeout')
        mocky.assert_called_once_with(mock_session)
        assert mock_session.absolute_timeout == 'timeout' 
Example #11
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_sh_validate_invalid(session_handler, mock_session, monkeypatch,
                             session_key):
    """
    unit test:  validate

    test case:
    do_validate raises expired session exception, calling on_expiration and
    raising
    """
    sh = session_handler

    with mock.patch.object(mock_session, 'validate') as ms_dv:
        ms_dv.side_effect = StoppedSessionException
        with mock.patch.object(NativeSessionHandler, 'on_invalidation') as sh_oe:
            sh_oe.return_value = None
            with pytest.raises(InvalidSessionException):

                sh.validate(mock_session, 'sessionkey123')

                sh_oe.assert_called_once_with(mock_session,
                                              ExpiredSessionException,
                                              'sessionkey123') 
Example #12
Source File: test_session_manager.py    From yosai with Apache License 2.0 6 votes vote down vote up
def test_sh_validate_expired(session_handler, mock_session, monkeypatch,
                             session_key):
    """
    unit test:  validate

    test case:
    do_validate raises expired session exception, calling on_expiration and
    raising
    """
    sh = session_handler

    with mock.patch.object(mock_session, 'validate') as ms_dv:
        ms_dv.side_effect = ExpiredSessionException
        with mock.patch.object(NativeSessionHandler, 'on_expiration') as sh_oe:
            sh_oe.return_value = None
            with pytest.raises(ExpiredSessionException):

                sh.validate(mock_session, 'sessionkey123')

                sh_oe.assert_called_once_with(mock_session,
                                              ExpiredSessionException,
                                              'sessionkey123') 
Example #13
Source File: testmock.py    From Imogen with MIT License 5 votes vote down vote up
def test_mock_open_write(self):
        # Test exception in file writing write()
        mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
        with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
            mock_filehandle = mock_namedtemp.return_value
            mock_write = mock_filehandle.write
            mock_write.side_effect = OSError('Test 2 Error')
            def attempt():
                tempfile.NamedTemporaryFile().write('asd')
            self.assertRaises(OSError, attempt) 
Example #14
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_mock_parents(self):
        for Klass in Mock, MagicMock:
            m = Klass()
            original_repr = repr(m)
            m.return_value = m
            self.assertIs(m(), m)
            self.assertEqual(repr(m), original_repr)

            m.reset_mock()
            self.assertIs(m(), m)
            self.assertEqual(repr(m), original_repr)

            m = Klass()
            m.b = m.a
            self.assertIn("name='mock.a'", repr(m.b))
            self.assertIn("name='mock.a'", repr(m.a))
            m.reset_mock()
            self.assertIn("name='mock.a'", repr(m.b))
            self.assertIn("name='mock.a'", repr(m.a))

            m = Klass()
            original_repr = repr(m)
            m.a = m()
            m.a.return_value = m

            self.assertEqual(repr(m), original_repr)
            self.assertEqual(repr(m.a()), original_repr) 
Example #15
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_attach_mock_return_value(self):
        classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
        for Klass in Mock, MagicMock:
            for Klass2 in classes:
                m = Klass()

                m2 = Klass2(name='foo')
                m.attach_mock(m2, 'return_value')

                self.assertIs(m(), m2)
                self.assertIn("name='mock()'", repr(m2))

                m2.foo()
                self.assertEqual(m.mock_calls, call().foo().call_list()) 
Example #16
Source File: testmock.py    From Imogen with MIT License 5 votes vote down vote up
def test_constructor(self):
        mock = Mock()

        self.assertFalse(mock.called, "called not initialised correctly")
        self.assertEqual(mock.call_count, 0,
                         "call_count not initialised correctly")
        self.assertTrue(is_instance(mock.return_value, Mock),
                        "return_value not initialised correctly")

        self.assertEqual(mock.call_args, None,
                         "call_args not initialised correctly")
        self.assertEqual(mock.call_args_list, [],
                         "call_args_list not initialised correctly")
        self.assertEqual(mock.method_calls, [],
                          "method_calls not initialised correctly")

        # Can't use hasattr for this test as it always returns True on a mock
        self.assertNotIn('_items', mock.__dict__,
                         "default mock should not have '_items' attribute")

        self.assertIsNone(mock._mock_parent,
                          "parent not initialised correctly")
        self.assertIsNone(mock._mock_methods,
                          "methods not initialised correctly")
        self.assertEqual(mock._mock_children, {},
                         "children not initialised incorrectly") 
Example #17
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_magic_methods_mock_calls(self):
        for Klass in Mock, MagicMock:
            m = Klass()
            m.__int__ = Mock(return_value=3)
            m.__float__ = MagicMock(return_value=3.0)
            int(m)
            float(m)

            self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
            self.assertEqual(m.method_calls, []) 
Example #18
Source File: testmock.py    From Imogen with MIT License 5 votes vote down vote up
def test_attach_mock_return_value(self):
        classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
        for Klass in Mock, MagicMock:
            for Klass2 in classes:
                m = Klass()

                m2 = Klass2(name='foo')
                m.attach_mock(m2, 'return_value')

                self.assertIs(m(), m2)
                self.assertIn("name='mock()'", repr(m2))

                m2.foo()
                self.assertEqual(m.mock_calls, call().foo().call_list()) 
Example #19
Source File: testmock.py    From Imogen with MIT License 5 votes vote down vote up
def test_mock_parents(self):
        for Klass in Mock, MagicMock:
            m = Klass()
            original_repr = repr(m)
            m.return_value = m
            self.assertIs(m(), m)
            self.assertEqual(repr(m), original_repr)

            m.reset_mock()
            self.assertIs(m(), m)
            self.assertEqual(repr(m), original_repr)

            m = Klass()
            m.b = m.a
            self.assertIn("name='mock.a'", repr(m.b))
            self.assertIn("name='mock.a'", repr(m.a))
            m.reset_mock()
            self.assertIn("name='mock.a'", repr(m.b))
            self.assertIn("name='mock.a'", repr(m.a))

            m = Klass()
            original_repr = repr(m)
            m.a = m()
            m.a.return_value = m

            self.assertEqual(repr(m), original_repr)
            self.assertEqual(repr(m.a()), original_repr) 
Example #20
Source File: testmock.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_constructor(self):
        mock = Mock()

        self.assertFalse(mock.called, "called not initialised correctly")
        self.assertEqual(mock.call_count, 0,
                         "call_count not initialised correctly")
        self.assertTrue(is_instance(mock.return_value, Mock),
                        "return_value not initialised correctly")

        self.assertEqual(mock.call_args, None,
                         "call_args not initialised correctly")
        self.assertEqual(mock.call_args_list, [],
                         "call_args_list not initialised correctly")
        self.assertEqual(mock.method_calls, [],
                          "method_calls not initialised correctly")

        # Can't use hasattr for this test as it always returns True on a mock
        self.assertNotIn('_items', mock.__dict__,
                         "default mock should not have '_items' attribute")

        self.assertIsNone(mock._mock_parent,
                          "parent not initialised correctly")
        self.assertIsNone(mock._mock_methods,
                          "methods not initialised correctly")
        self.assertEqual(mock._mock_children, {},
                         "children not initialised incorrectly") 
Example #21
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_mock_open_alter_readline(self):
        mopen = mock.mock_open(read_data='foo\nbarn')
        mopen.return_value.readline.side_effect = lambda *args:'abc'
        first = mopen().readline()
        second = mopen().readline()
        self.assertEqual('abc', first)
        self.assertEqual('abc', second) 
Example #22
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_mock_open_write(self):
        # Test exception in file writing write()
        mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
        with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
            mock_filehandle = mock_namedtemp.return_value
            mock_write = mock_filehandle.write
            mock_write.side_effect = OSError('Test 2 Error')
            def attempt():
                tempfile.NamedTemporaryFile().write('asd')
            self.assertRaises(OSError, attempt) 
Example #23
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_reset_mock(self):
        parent = Mock()
        spec = ["something"]
        mock = Mock(name="child", parent=parent, spec=spec)
        mock(sentinel.Something, something=sentinel.SomethingElse)
        something = mock.something
        mock.something()
        mock.side_effect = sentinel.SideEffect
        return_value = mock.return_value
        return_value()

        mock.reset_mock()

        self.assertEqual(mock._mock_name, "child",
                         "name incorrectly reset")
        self.assertEqual(mock._mock_parent, parent,
                         "parent incorrectly reset")
        self.assertEqual(mock._mock_methods, spec,
                         "methods incorrectly reset")

        self.assertFalse(mock.called, "called not reset")
        self.assertEqual(mock.call_count, 0, "call_count not reset")
        self.assertEqual(mock.call_args, None, "call_args not reset")
        self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
        self.assertEqual(mock.method_calls, [],
                        "method_calls not initialised correctly: %r != %r" %
                        (mock.method_calls, []))
        self.assertEqual(mock.mock_calls, [])

        self.assertEqual(mock.side_effect, sentinel.SideEffect,
                          "side_effect incorrectly reset")
        self.assertEqual(mock.return_value, return_value,
                          "return_value incorrectly reset")
        self.assertFalse(return_value.called, "return value mock not reset")
        self.assertEqual(mock._mock_children, {'something': something},
                          "children reset incorrectly")
        self.assertEqual(mock.something, something,
                          "children incorrectly cleared")
        self.assertFalse(mock.something.called, "child not reset") 
Example #24
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_mock_add_spec_magic_methods(self):
        for Klass in MagicMock, NonCallableMagicMock:
            mock = Klass()
            int(mock)

            mock.mock_add_spec(object)
            self.assertRaises(TypeError, int, mock)

            mock = Klass()
            mock['foo']
            mock.__int__.return_value =4

            mock.mock_add_spec(int)
            self.assertEqual(int(mock), 4)
            self.assertRaises(TypeError, lambda: mock['foo']) 
Example #25
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_side_effect_iterator_default(self):
        mock = Mock(return_value=2)
        mock.side_effect = iter([1, DEFAULT])
        self.assertEqual([mock(), mock()], [1, 2]) 
Example #26
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_configure_mock(self):
        mock = Mock(foo='bar')
        self.assertEqual(mock.foo, 'bar')

        mock = MagicMock(foo='bar')
        self.assertEqual(mock.foo, 'bar')

        kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
                  'foo': MagicMock()}
        mock = Mock(**kwargs)
        self.assertRaises(KeyError, mock)
        self.assertEqual(mock.foo.bar(), 33)
        self.assertIsInstance(mock.foo, MagicMock)

        mock = Mock()
        mock.configure_mock(**kwargs)
        self.assertRaises(KeyError, mock)
        self.assertEqual(mock.foo.bar(), 33)
        self.assertIsInstance(mock.foo, MagicMock) 
Example #27
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_wraps_call_with_nondefault_return_value(self):
        real = Mock()

        mock = Mock(wraps=real)
        mock.return_value = 3

        self.assertEqual(mock(), 3)
        self.assertFalse(real.called) 
Example #28
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_attribute_access_returns_mocks(self):
        mock = Mock()
        something = mock.something
        self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
        self.assertEqual(mock.something, something,
                         "different attributes returned for same name")

        # Usage example
        mock = Mock()
        mock.something.return_value = 3

        self.assertEqual(mock.something(), 3, "method returned wrong value")
        self.assertTrue(mock.something.called,
                        "method didn't record being called") 
Example #29
Source File: testmock.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_reset_mock_recursion(self):
        mock = Mock()
        mock.return_value = mock

        # used to cause recursion
        mock.reset_mock() 
Example #30
Source File: testmock.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_reset_mock_recursion(self):
        mock = Mock()
        mock.return_value = mock

        # used to cause recursion
        mock.reset_mock()