本文整理汇总了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
示例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)
示例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)
示例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)
示例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()
示例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)
示例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()
示例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)
示例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.
示例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)
示例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)
示例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)
示例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
示例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"
示例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)