Python unittest.mock 模块,return_value() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用unittest.mock.return_value()

项目:concierge    作者:9seconds    | 项目源码 | 文件源码
def inotifier(request):
    mock = have_mocked(request, "inotify_simple.INotify")
    mock.return_value = mock
    mock.__enter__.return_value = mock

    values = [inotify_simple.Event(0, 0, 0,
                                   os.path.basename(concierge.DEFAULT_RC))]
    values *= 3

    def side_effect():
        if values:
            return [values.pop()]
        raise KeyboardInterrupt

    mock.read.side_effect = side_effect
    mock.v = values

    return mock
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
def test_authenticate_ok(mocked_authenticator, configure_model,
                         sudo_user_with_external_id):
    now, expired = make_now_expired()

    mock = mocked_authenticator.client.get_raw_token_from_identity_service
    mock.return_value = make_token_data(
        sudo_user_with_external_id, now, expired)

    model = mocked_authenticator.authenticate("sudo", "sudo")
    assert model.model_id == model._id == mock.return_value["id"]
    assert model.user.model_id == sudo_user_with_external_id.model_id
    # calendar.timegm because expired is naive datetime
    assert int(model.expires_at.timestamp()) == int(calendar.timegm(
        expired.timetuple()))

    # We do not store tokens for keystone
    assert not token.TokenModel.find_token(model.model_id)
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
def test_require_authentication_ok(
        mocked_authenticator, configure_model, sudo_client_v1,
        sudo_user_with_external_id, app):
    now, expired = make_now_expired()
    endpoint = "/" + pytest.faux.gen_alphanumeric()

    mock = mocked_authenticator.client.tokens.get_token_data
    mock.return_value = {
        "token": make_token_data(sudo_user_with_external_id, now, expired)
    }

    @app.route(endpoint)
    @mocked_authenticator.require_authentication
    def testing_endpoint():
        assert int(flask.g.token.expires_at.timestamp()) == int(
            calendar.timegm(expired.timetuple()))
        assert flask.g.token.user_id == sudo_user_with_external_id.model_id
        return flask.jsonify(value=1)

    response = sudo_client_v1.get(endpoint)
    assert response.status_code == 200
    assert response.json == {"value": 1}

    mock = mocked_authenticator.client.tokens.get_token_data
    mock.assert_called_once_with(sudo_client_v1.auth_token)
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
def test_require_authentication_unknown_user(
        mocked_authenticator, configure_model, sudo_client_v1,
        sudo_user_with_external_id, app):
    now, expired = make_now_expired()
    endpoint = "/" + pytest.faux.gen_alphanumeric()

    mock = mocked_authenticator.client.tokens.get_token_data
    mock.return_value = {
        "token": make_token_data(sudo_user_with_external_id, now, expired)
    }
    mock.return_value["token"]["user"]["id"] += "FAKE"

    @app.route(endpoint)
    @mocked_authenticator.require_authentication
    def testing_endpoint():
        assert int(flask.g.token.expires_at.timestamp()) == int(
            calendar.timegm(expired.timetuple()))
        assert flask.g.token.user_id == sudo_user_with_external_id.model_id
        return flask.jsonify(value=1)

    response = sudo_client_v1.get(endpoint)
    assert response.status_code == 401

    mock = mocked_authenticator.client.tokens.get_token_data
    mock.assert_called_once_with(sudo_client_v1.auth_token)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:concierge    作者:9seconds    | 项目源码 | 文件源码
def mock_mainfunc(cliargs_default, mock_get_content, inotifier):
    mock_get_content.return_value = """\
Compression yes

Host q
    HostName e

    Host b
        HostName lalala
    """

    return cliargs_default, mock_get_content, inotifier
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def test_can_decode_utf8_strings_with_french_content(self, encoding_mocker_stopall):
        # mock
        mock_getpreferredencoding = encoding_mocker_stopall.MagicMock(name="mock_getpreferredencoding")
        # patch
        encoding_mocker_stopall.patch.object(scarlett_os.internal.encoding.locale, 'getpreferredencoding', mock_getpreferredencoding)

        mock.return_value = 'UTF-8'

        # source: http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
        # NOTE: In Python 2.x, prefixing a string literal with a "b" (or "B") is legal syntax, but it does nothing special:
        # NOTE: In Python 3.x, however, this prefix indicates the string is a bytes object which differs from the normal string (which as we know is by default a Unicode string), and even the 'b' prefix is preserved:
        result = encoding.locale_decode(
            b'[Errno 98] Adresse d\xc3\xa9j\xc3\xa0 utilis\xc3\xa9e')

        assert "b'[Errno 98] Adresse d\\xc3\\xa9j\\xc3\\xa0 utilis\\xc3\\xa9e'" == result

    # def test_can_decode_an_ioerror_with_french_content(self, mock):
    #     mock.return_value = 'UTF-8'
    #
    #     error = IOError(98, b'Adresse d\xc3\xa9j\xc3\xa0 utilis\xc3\xa9e')
    #     result = encoding.locale_decode(error)
    #     expected = '[Errno 98] Adresse d\xe9j\xe0 utilis\xe9e'
    #
    #     self.assertEqual(
    #         expected, result,
    #         '%r decoded to %r does not match expected %r' % (
    #             error, result, expected))
    #
    # def test_does_not_use_locale_to_decode_unicode_strings(self, mock):
    #     mock.return_value = 'UTF-8'
    #
    #     encoding.locale_decode('abc')
    #
    #     self.assertFalse(mock.called)
    #
    # def test_does_not_use_locale_to_decode_ascii_bytestrings(self, mock):
    #     mock.return_value = 'UTF-8'
    #
    #     encoding.locale_decode('abc')
    #
    #     self.assertFalse(mock.called)
项目:axelrod-api    作者:Axelrod-Python    | 项目源码 | 文件源码
def test_string_word_to_boolean(self, filtered_strategies_mock):
        filtered_strategies_mock.return_value = mock.MagicMock()

        request = self.factory.get('/articles/?stochastic=true')
        request.query_params = request.GET  # factory doesn't support query_params
        filter_strategies(request)
        filtered_strategies_mock.assert_called_with({'stochastic': 1})
项目:axelrod-api    作者:Axelrod-Python    | 项目源码 | 文件源码
def test_string_number_to_boolean(self, filtered_strategies_mock):
        mock.return_value = mock.MagicMock()

        request = self.factory.get('/articles/?stochastic=1')
        request.query_params = request.GET  # factory doesn't support query_params
        filter_strategies(request)
        filtered_strategies_mock.assert_called_with({'stochastic': 1})
项目:axelrod-api    作者:Axelrod-Python    | 项目源码 | 文件源码
def test_string_to_int(self, filtered_strategies_mock):
        filtered_strategies_mock.return_value = mock.MagicMock()

        request = self.factory.get('/articles/?memory_depth=3')
        request.query_params = request.GET  # factory doesn't support query_params
        filter_strategies(request)
        filtered_strategies_mock.assert_called_with({'memory_depth': 3})
项目:axelrod-api    作者:Axelrod-Python    | 项目源码 | 文件源码
def test_makes_use_of(self, filtered_strategies_mock):
        filtered_strategies_mock.return_value = mock.MagicMock()

        request = self.factory.get('/articles/?makes_use_of=game')
        request.query_params = request.GET  # factory doesn't support query_params
        filter_strategies(request)
        filtered_strategies_mock.assert_called_with({'makes_use_of': ['game']})
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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.assertFalse('_items' in 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")
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_return_value_in_constructor(self):
        mock = Mock(return_value=None)
        self.assertIsNone(mock.return_value,
                          "return value in constructor not honoured")
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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")
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_reset_mock_recursion(self):
        mock = Mock()
        mock.return_value = mock

        # used to cause recursion
        mock.reset_mock()
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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")
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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'])
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_adding_return_value_mock(self):
        for Klass in Mock, MagicMock:
            mock = Klass()
            mock.return_value = MagicMock()

            mock()()
            self.assertEqual(mock.mock_calls, [call(), call()()])
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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())
项目:ceph-lcm    作者:Mirantis    | 项目源码 | 文件源码
def test_logout(mocked_authenticator, configure_model,
                sudo_user_with_external_id):
    now, expired = make_now_expired()
    mock = mocked_authenticator.client.get_raw_token_from_identity_service
    mock.return_value = make_token_data(
        sudo_user_with_external_id, now, expired)
    model = mocked_authenticator.authenticate("sudo", "sudo")
    mocked_authenticator.client.tokens.revoke_token.assert_not_called()

    mocked_authenticator.logout(model)
    mocked_authenticator.client.tokens.revoke_token.assert_called_once_with(
        model.model_id)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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")
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_return_value_in_constructor(self):
        mock = Mock(return_value=None)
        self.assertIsNone(mock.return_value,
                          "return value in constructor not honoured")
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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")
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_reset_mock_recursion(self):
        mock = Mock()
        mock.return_value = mock

        # used to cause recursion
        mock.reset_mock()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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")
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_side_effect_iterator_default(self):
        mock = Mock(return_value=2)
        mock.side_effect = iter([1, DEFAULT])
        self.assertEqual([mock(), mock()], [1, 2])
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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'])
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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, [])
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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())
项目:SMAC3    作者:automl    | 项目源码 | 文件源码
def test_run_execute_func_for_fmin(self, mock):
        mock.return_value = {'x1': 2, 'x2': 1}
        c = Configuration(configuration_space=self.cs, values={})
        target = lambda x: x[0] ** 2 + x[1]
        taf = ExecuteTAFuncArray(target, stats=self.stats)
        rval = taf._call_ta(target, c)
        self.assertEqual(rval, 5)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_return_value_in_constructor(self):
        mock = Mock(return_value=None)
        self.assertIsNone(mock.return_value,
                          "return value in constructor not honoured")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_reset_mock_recursion(self):
        mock = Mock()
        mock.return_value = mock

        # used to cause recursion
        mock.reset_mock()
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_side_effect_iterator_default(self):
        mock = Mock(return_value=2)
        mock.side_effect = iter([1, DEFAULT])
        self.assertEqual([mock(), mock()], [1, 2])
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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'])
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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, [])