當前位置: 首頁>>代碼示例>>Python>>正文


Python mock.return_value方法代碼示例

本文整理匯總了Python中mock.return_value方法的典型用法代碼示例。如果您正苦於以下問題:Python mock.return_value方法的具體用法?Python mock.return_value怎麽用?Python mock.return_value使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mock的用法示例。


在下文中一共展示了mock.return_value方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: configure_mock

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def configure_mock(self, **kwargs):
        """Set attributes on the mock through keyword arguments.

        Attributes plus return values and side effects can be set on child
        mocks using standard dot notation and unpacking a dictionary in the
        method call:

        >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
        >>> mock.configure_mock(**attrs)"""
        for arg, val in sorted(kwargs.items(),
                               # we sort on the number of dots so that
                               # attributes are set before we set attributes on
                               # attributes
                               key=lambda entry: entry[0].count('.')):
            args = arg.split('.')
            final = args.pop()
            obj = self
            for entry in args:
                obj = getattr(obj, entry)
            setattr(obj, final, val) 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:22,代碼來源:mock.py

示例2: test_configure_mock

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
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) 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:21,代碼來源:testmock.py

示例3: primary_google_service_account

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def primary_google_service_account(app, db_session, user_client, google_proxy_group):
    service_account_id = "test-service-account-0"
    email = fence.utils.random_str(40) + "@test.com"
    service_account = models.GoogleServiceAccount(
        google_unique_id=service_account_id,
        email=email,
        user_id=user_client.user_id,
        client_id=None,
        google_project_id="projectId-0",
    )
    db_session.add(service_account)
    db_session.commit()

    mock = MagicMock()
    mock.return_value = service_account
    patcher = patch("fence.resources.google.utils.get_or_create_service_account", mock)
    patcher.start()

    yield Dict(
        id=service_account_id, email=email, get_or_create_service_account_mock=mock
    )

    patcher.stop() 
開發者ID:uc-cdis,項目名稱:fence,代碼行數:25,代碼來源:conftest.py

示例4: cloud_manager

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def cloud_manager():
    manager = MagicMock()
    patch("fence.blueprints.storage_creds.google.GoogleCloudManager", manager).start()
    patch("fence.resources.google.utils.GoogleCloudManager", manager).start()
    patch("fence.scripting.fence_create.GoogleCloudManager", manager).start()
    patch("fence.scripting.google_monitor.GoogleCloudManager", manager).start()
    patch("fence.resources.admin.admin_users.GoogleCloudManager", manager).start()
    patch("fence.resources.google.access_utils.GoogleCloudManager", manager).start()
    patch("fence.resources.google.validity.GoogleCloudManager", manager).start()
    patch("fence.blueprints.google.GoogleCloudManager", manager).start()
    manager.return_value.__enter__.return_value.get_access_key.return_value = {
        "type": "service_account",
        "project_id": "project-id",
        "private_key_id": "some_number",
        "private_key": "-----BEGIN PRIVATE KEY-----\n....\n-----END PRIVATE KEY-----\n",
        "client_email": "<api-name>api@project-id.iam.gserviceaccount.com",
        "client_id": "...",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/...<api-name>api%40project-id.iam.gserviceaccount.com",
    }
    return manager 
開發者ID:uc-cdis,項目名稱:fence,代碼行數:25,代碼來源:conftest.py

示例5: _set_return_value

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def _set_return_value(mock, method, name):
    fixed = _return_values.get(name, DEFAULT)
    if fixed is not DEFAULT:
        method.return_value = fixed
        return

    return_calulator = _calculate_return_value.get(name)
    if return_calulator is not None:
        try:
            return_value = return_calulator(mock)
        except AttributeError:
            # XXXX why do we return AttributeError here?
            #      set it as a side_effect instead?
            # Answer: it makes magic mocks work on pypy?!
            return_value = AttributeError(name)
        method.return_value = return_value
        return

    side_effector = _side_effect_methods.get(name)
    if side_effector is not None:
        method.side_effect = side_effector(mock) 
開發者ID:ali5h,項目名稱:rules_pip,代碼行數:23,代碼來源:mock.py

示例6: test_oidc_with_refresh

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def test_oidc_with_refresh(self, mock_ApiClient, mock_OAuth2Session):
        mock_response = mock.MagicMock()
        type(mock_response).status = mock.PropertyMock(
            return_value=200
        )
        type(mock_response).data = mock.PropertyMock(
            return_value=json.dumps({
                "token_endpoint": "https://example.org/identity/token"
            })
        )

        mock_ApiClient.return_value = mock_response

        mock_OAuth2Session.return_value = {"id_token": "abc123",
                                           "refresh_token": "newtoken123"}

        loader = KubeConfigLoader(
            config_dict=self.TEST_KUBE_CONFIG,
            active_context="expired_oidc",
        )
        self.assertTrue(loader._load_auth_provider_token())
        self.assertEqual("Bearer abc123", loader.token) 
開發者ID:kubernetes-client,項目名稱:python-base,代碼行數:24,代碼來源:kube_config_test.py

示例7: test_oidc_with_refresh_nocert

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def test_oidc_with_refresh_nocert(
            self, mock_ApiClient, mock_OAuth2Session):
        mock_response = mock.MagicMock()
        type(mock_response).status = mock.PropertyMock(
            return_value=200
        )
        type(mock_response).data = mock.PropertyMock(
            return_value=json.dumps({
                "token_endpoint": "https://example.org/identity/token"
            })
        )

        mock_ApiClient.return_value = mock_response

        mock_OAuth2Session.return_value = {"id_token": "abc123",
                                           "refresh_token": "newtoken123"}

        loader = KubeConfigLoader(
            config_dict=self.TEST_KUBE_CONFIG,
            active_context="expired_oidc_nocert",
        )
        self.assertTrue(loader._load_auth_provider_token())
        self.assertEqual("Bearer abc123", loader.token) 
開發者ID:kubernetes-client,項目名稱:python-base,代碼行數:25,代碼來源:kube_config_test.py

示例8: _setup_func

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def _setup_func(funcopy, mock):
    funcopy.mock = mock

    # can't use isinstance with mocks
    if not _is_instance_mock(mock):
        return

    def assert_called_with(*args, **kwargs):
        return mock.assert_called_with(*args, **kwargs)
    def assert_called_once_with(*args, **kwargs):
        return mock.assert_called_once_with(*args, **kwargs)
    def assert_has_calls(*args, **kwargs):
        return mock.assert_has_calls(*args, **kwargs)
    def assert_any_call(*args, **kwargs):
        return mock.assert_any_call(*args, **kwargs)
    def reset_mock():
        funcopy.method_calls = _CallList()
        funcopy.mock_calls = _CallList()
        mock.reset_mock()
        ret = funcopy.return_value
        if _is_instance_mock(ret) and not ret is mock:
            ret.reset_mock()

    funcopy.called = False
    funcopy.call_count = 0
    funcopy.call_args = None
    funcopy.call_args_list = _CallList()
    funcopy.method_calls = _CallList()
    funcopy.mock_calls = _CallList()

    funcopy.return_value = mock.return_value
    funcopy.side_effect = mock.side_effect
    funcopy._mock_children = mock._mock_children

    funcopy.assert_called_with = assert_called_with
    funcopy.assert_called_once_with = assert_called_once_with
    funcopy.assert_has_calls = assert_has_calls
    funcopy.assert_any_call = assert_any_call
    funcopy.reset_mock = reset_mock

    mock._mock_delegate = funcopy 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:43,代碼來源:mock.py

示例9: __get_return_value

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def __get_return_value(self):
        ret = self._mock_return_value
        if self._mock_delegate is not None:
            ret = self._mock_delegate.return_value

        if ret is DEFAULT:
            ret = self._get_child_mock(
                _new_parent=self, _new_name='()'
            )
            self.return_value = ret
        return ret 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:13,代碼來源:mock.py

示例10: __set_return_value

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def __set_return_value(self, value):
        if self._mock_delegate is not None:
            self._mock_delegate.return_value = value
        else:
            self._mock_return_value = value
            _check_and_set_parent(self, value, None, '()') 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:8,代碼來源:mock.py

示例11: __init__

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
                 wraps=None, name=None, spec_set=None, parent=None,
                 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
        self.__dict__['_mock_return_value'] = return_value

        _safe_super(CallableMixin, self).__init__(
            spec, wraps, name, spec_set, parent,
            _spec_state, _new_name, _new_parent, **kwargs
        )

        self.side_effect = side_effect 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:13,代碼來源:mock.py

示例12: test_constructor

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
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") 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:28,代碼來源:testmock.py

示例13: test_return_value_in_constructor

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
def test_return_value_in_constructor(self):
        mock = Mock(return_value=None)
        self.assertIsNone(mock.return_value,
                          "return value in constructor not honoured") 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:6,代碼來源:testmock.py

示例14: test_side_effect

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
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) 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:28,代碼來源:testmock.py

示例15: test_reset_mock

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import return_value [as 別名]
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") 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:41,代碼來源:testmock.py


注:本文中的mock.return_value方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。