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


Python asynctest.Mock方法代碼示例

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


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

示例1: _session_app

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def _session_app() -> Quart:
    app = Quart(__name__)
    app.session_interface = AsyncMock(spec=SessionInterface)
    app.session_interface.open_session.return_value = SecureCookieSession()  # type: ignore
    app.session_interface.is_null_session.return_value = False  # type: ignore

    @app.route("/")
    async def route() -> str:
        session["a"] = "b"
        return ""

    @app.websocket("/ws/")
    async def ws() -> None:
        session["a"] = "b"
        await websocket.accept()
        await websocket.send("")

    @app.websocket("/ws_return/")
    async def ws_return() -> str:
        session["a"] = "b"
        return ""

    return app 
開發者ID:pgjones,項目名稱:quart,代碼行數:25,代碼來源:test_app.py

示例2: test_refresh_token

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_refresh_token(self):
        loader = KubeConfigLoader(
            config_dict=self.TEST_KUBE_CONFIG,
            active_context="gcp",
            get_google_credentials=lambda: _raise_exception(
                "SHOULD NOT BE CALLED"))
        mock_sleep = patch('asyncio.sleep').start()
        mock_sleep.side_effect = [0, AssertionError]

        mock_config = Mock()
        mock_config.api_key = {}

        with self.assertRaises(AssertionError):
            await refresh_token(loader, mock_config)

        self.assertEqual(BEARER_TOKEN_FORMAT % TEST_DATA_BASE64,
                         loader.token) 
開發者ID:tomplus,項目名稱:kubernetes_asyncio,代碼行數:19,代碼來源:kube_config_test.py

示例3: test_initialization

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_initialization(self):
        mode = "x"
        encoding = "utf-8"
        loop = Mock()
        handler = AsyncFileHandler(
            filename=self.temp_file.name,
            mode=mode,
            encoding=encoding,
            loop=loop,
        )

        self.assertIsInstance(handler, AsyncFileHandler)

        self.assertEqual(handler.absolute_file_path, self.temp_file.name)
        self.assertEqual(handler.mode, mode)
        self.assertEqual(handler.encoding, encoding)
        self.assertEqual(handler.loop, loop)

        self.assertIsNone(handler.stream) 
開發者ID:b2wdigital,項目名稱:aiologger,代碼行數:21,代碼來源:test_files.py

示例4: test_emit_awaits_for_handle_error_is_an_exceptions_is_raised

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_emit_awaits_for_handle_error_is_an_exceptions_is_raised(
        self
    ):
        handler = BaseAsyncRotatingFileHandler(filename=self.temp_file.name)
        handler.should_rollover = Mock(return_value=False)
        exc = OSError()
        with patch(
            "aiologger.handlers.files.AsyncFileHandler.emit", side_effect=exc
        ), patch.object(
            handler, "handle_error", CoroutineMock()
        ) as handleError:
            log_record = LogRecord(
                name="Xablau",
                level=20,
                pathname="/aiologger/tests/test_logger.py",
                lineno=17,
                msg="Xablau!",
                exc_info=None,
                args=None,
            )
            await handler.emit(log_record)
            handleError.assert_awaited_once_with(log_record, exc) 
開發者ID:b2wdigital,項目名稱:aiologger,代碼行數:24,代碼來源:test_files.py

示例5: test_callhandlers_calls_handlers_for_loglevel

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_callhandlers_calls_handlers_for_loglevel(self):
        level10_handler = Mock(level=10, handle=CoroutineMock())
        level30_handler = Mock(level=30, handle=CoroutineMock())

        logger = Logger.with_default_handlers()
        logger.handlers = [level10_handler, level30_handler]

        record = LogRecord(
            level=20,
            name="aiologger",
            pathname="/aiologger/tests/test_logger.py",
            lineno=17,
            msg="Xablau!",
            exc_info=None,
            args=None,
        )
        await logger.call_handlers(record)

        level10_handler.handle.assert_awaited_once_with(record)
        level30_handler.handle.assert_not_awaited() 
開發者ID:b2wdigital,項目名稱:aiologger,代碼行數:22,代碼來源:test_logger.py

示例6: test_it_calls_multiple_handlers_if_multiple_handle_matches_are_found_for_record

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_it_calls_multiple_handlers_if_multiple_handle_matches_are_found_for_record(
        self
    ):
        level10_handler = Mock(level=10, handle=CoroutineMock())
        level20_handler = Mock(level=20, handle=CoroutineMock())

        logger = Logger.with_default_handlers()
        logger.handlers = [level10_handler, level20_handler]

        record = LogRecord(
            level=30,
            name="aiologger",
            pathname="/aiologger/tests/test_logger.py",
            lineno=17,
            msg="Xablau!",
            exc_info=None,
            args=None,
        )

        await logger.call_handlers(record)

        level10_handler.handle.assert_awaited_once_with(record)
        level20_handler.handle.assert_awaited_once_with(record) 
開發者ID:b2wdigital,項目名稱:aiologger,代碼行數:25,代碼來源:test_logger.py

示例7: test_shutdown_doest_not_closes_handlers_if_not_initialized

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_shutdown_doest_not_closes_handlers_if_not_initialized(self):
        initialized_handler = Mock(spec=AsyncStreamHandler)
        not_initialized_handler = Mock(
            spec=AsyncStreamHandler, initialized=False
        )

        logger = Logger()
        logger.handlers = [initialized_handler, not_initialized_handler]

        await logger.shutdown()

        initialized_handler.flush.assert_awaited_once()
        initialized_handler.close.assert_awaited_once()

        not_initialized_handler.flush.assert_not_awaited()
        not_initialized_handler.close.assert_not_awaited() 
開發者ID:b2wdigital,項目名稱:aiologger,代碼行數:18,代碼來源:test_logger.py

示例8: setUp

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def setUp(self):
        self.get_free_space = CoroutineMock()

        class FreeSpaceAPI(FreeSpaceAPIBase):
            get_free_space = self.get_free_space

        self.path_getters = (Mock(return_value='/foo', name='Mock for /foo'),
                             Mock(return_value='/bar', name='Mock for /bar'))
        rpc = None  # Should not be used in these tests
        self.mock_settings = Mock()
        self.freespace = FreeSpaceAPI(self.path_getters, rpc, self.mock_settings)
        # We need a spec from a callable because blinker does some weird stuff and we get
        # an AttributeError for '__self__' without the spec.  Also, RequestPoller
        # prettifies function calls in the logs, so we need the __qualname__.
        self.update_cb = Mock(spec=lambda self: None, __qualname__='mock_callback')
        self.freespace.on_update(self.update_cb) 
開發者ID:rndusr,項目名稱:stig,代碼行數:18,代碼來源:base_test.py

示例9: test_mock_returns_coroutine_according_to_spec

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_mock_returns_coroutine_according_to_spec(self, klass):
        spec = Test()

        for attr in ('spec', 'spec_set', ):
            with self.subTest(spec_type=attr):
                mock = klass(**{attr: spec})

                self.assertIsInstance(mock.a_function, (asynctest.Mock, asynctest.MagicMock))
                self.assertNotIsInstance(mock.a_function, asynctest.CoroutineMock)
                self.assertIsInstance(mock.a_coroutine, asynctest.CoroutineMock)
                self.assertIsInstance(mock.a_classmethod_coroutine, asynctest.CoroutineMock)
                self.assertIsInstance(mock.a_staticmethod_coroutine, asynctest.CoroutineMock)
                mock.a_coroutine.return_value = "PROBE"
                self.assertEqual("PROBE", run_coroutine(mock.a_coroutine()))

                self.assertIsInstance(mock.an_async_coroutine, asynctest.CoroutineMock)
                self.assertIsInstance(mock.an_async_classmethod_coroutine, asynctest.CoroutineMock)
                self.assertIsInstance(mock.an_async_staticmethod_coroutine, asynctest.CoroutineMock)
                mock.an_async_coroutine.return_value = "PROBE"
                self.assertEqual("PROBE", run_coroutine(mock.an_async_coroutine()))

    # Ensure the name of the mock is correctly set, tests bug #49. 
開發者ID:Martiusweb,項目名稱:asynctest,代碼行數:24,代碼來源:test_mock.py

示例10: test_autospec_coroutine

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_autospec_coroutine(self):
        called = False

        @asynctest.mock.patch(self.test_class_path, autospec=True)
        def patched(mock):
            nonlocal called
            called = True
            self.assertIsInstance(mock.a_coroutine,
                                  asynctest.mock.CoroutineMock)

            self.assertIsInstance(mock().a_coroutine,
                                  asynctest.mock.CoroutineMock)

            self.assertIsInstance(mock.a_function, asynctest.mock.Mock)
            self.assertIsInstance(mock().a_function, asynctest.mock.Mock)
            self.assertIsInstance(mock.an_async_coroutine, asynctest.mock.CoroutineMock)
            self.assertIsInstance(mock().an_async_coroutine, asynctest.mock.CoroutineMock)

        patched()
        self.assertTrue(called) 
開發者ID:Martiusweb,項目名稱:asynctest,代碼行數:22,代碼來源:test_mock.py

示例11: test_patch_autospec_with_patches_under

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_patch_autospec_with_patches_under(self):
        called = False

        @asynctest.mock.patch("{}.{}".format(self.test_class_path, "a_coroutine"),
                              autospec=True)
        @asynctest.mock.patch("{}.{}".format(self.test_class_path, "is_patched"),
                              return_value=True)
        def patched_function(is_patched_mock, coroutine_mock):
            nonlocal called
            called = True

            self.assertIsInstance(Test.is_patched, asynctest.mock.Mock)
            self.assertTrue(Test.is_patched())
            self.assertTrue(asyncio.iscoroutinefunction(coroutine_mock))
            self.assertTrue(asyncio.iscoroutinefunction(Test.a_coroutine))

        patched_function()
        self.assertTrue(called) 
開發者ID:Martiusweb,項目名稱:asynctest,代碼行數:20,代碼來源:test_mock.py

示例12: test_no_users_to_add

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_no_users_to_add(self):
        client = asynctest.Mock(Client())

        client.get_users.return_value = asyncio.Future()
        client.get_users.return_value.set_result([])

        client.increase_nb_users_cached.return_value = asyncio.Future()
        client.increase_nb_users_cached.return_value.set_result(None)

        cache = {}

        nb_added = await cache_users_async(client, cache)

        client.get_users.assert_called()
        self.assertEqual(nb_added, 0)
        self.assertEqual(len(cache), 0)

        client.increase_nb_users_cached.assert_called_once_with(0) 
開發者ID:Martiusweb,項目名稱:asynctest,代碼行數:20,代碼來源:mocking.py

示例13: dummy_zmq_server

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def dummy_zmq_server(monkeypatch):
    """
    A fixture which provides a dummy zero mq
    socket which records the json it is asked
    to send.

    Parameters
    ----------
    monkeypatch

    Yields
    ------
    asynctest.CoroutineMock
        Coroutine mocking for the recv_json method of the socket

    """
    dummy = Mock()
    dummy.return_value.socket.return_value.recv_json = CoroutineMock()

    monkeypatch.setattr(zmq.asyncio.Context, "instance", dummy)
    yield dummy.return_value.socket.return_value.recv_json 
開發者ID:Flowminder,項目名稱:FlowKit,代碼行數:23,代碼來源:conftest.py

示例14: test_query_run

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_query_run():
    """
    Test that the 'run' method runs the query and records the query ID internally.
    """
    connection_mock = AMock()
    connection_mock.post_json = CoroutineMock(
        return_value=Mock(
            status_code=202, headers={"Location": "DUMMY_LOCATION/DUMMY_ID"}
        )
    )
    query_spec = {"query_kind": "dummy_query"}
    query = ASyncAPIQuery(connection=connection_mock, parameters=query_spec)
    assert not hasattr(query, "_query_id")
    await query.run()
    connection_mock.post_json.assert_called_once_with(route="run", data=query_spec)
    assert query._query_id == "DUMMY_ID" 
開發者ID:Flowminder,項目名稱:FlowKit,代碼行數:18,代碼來源:test_async_api_query.py

示例15: test_query_get_result_runs

# 需要導入模塊: import asynctest [as 別名]
# 或者: from asynctest import Mock [as 別名]
def test_query_get_result_runs(monkeypatch):
    """
    Test that get_result runs the query if it's not already running.
    """
    get_result_mock = CoroutineMock(return_value="DUMMY_RESULT")
    monkeypatch.setattr(
        f"flowclient.async_api_query.get_result_by_query_id", get_result_mock
    )
    connection_mock = AMock()
    query_spec = {"query_kind": "dummy_query"}
    connection_mock.post_json = CoroutineMock(
        return_value=Mock(
            status_code=202, headers={"Location": "DUMMY_LOCATION/DUMMY_ID"}
        )
    )
    query = ASyncAPIQuery(connection=connection_mock, parameters=query_spec)
    await query.get_result()
    connection_mock.post_json.assert_called_once_with(route="run", data=query_spec) 
開發者ID:Flowminder,項目名稱:FlowKit,代碼行數:20,代碼來源:test_async_api_query.py


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