Python asynctest.Mock() Examples

The following are 30 code examples of asynctest.Mock(). 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 asynctest , or try the search function .
Example #1
Source File: test_scheduled.py    From async-worker with MIT License 6 votes vote down vote up
def test_run_dispatches_a_new_task_for_each_valid_clock_tick(self):
        clock = asynctest.MagicMock()
        clock.__aiter__.return_value = range(3)
        wrapped_task = Mock()
        with patch.multiple(
            self.task_runner,
            clock=clock,
            _wrapped_task=wrapped_task,
            can_dispatch_task=CoroutineMock(side_effect=[True, False, True]),
        ), patch(
            "asyncworker.task_runners.asyncio.ensure_future"
        ) as ensure_future:
            await self.task_runner._run()
            self.assertEqual(
                ensure_future.call_args_list,
                [
                    call(wrapped_task.return_value),
                    call(wrapped_task.return_value),
                ],
            ) 
Example #2
Source File: base_test.py    From stig with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
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. 
Example #4
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_query_ready_reports_false():
    """ Test that status code 202 is interpreted as query running. """
    con_mock = AMock()
    con_mock.get_url = CoroutineMock(
        return_value=AMock(
            status_code=202,
            json=Mock(
                return_value={
                    "status": "completed",
                    "progress": {"eligible": 0, "queued": 0, "running": 0},
                }
            ),
        )
    )
    is_ready, reply = await query_is_ready(connection=con_mock, query_id="foo")
    assert not is_ready 
Example #5
Source File: test_async_api_query.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_get_result_location_from_id_when_ready():
    """
    Any unexpected http code should raise an exception.
    """
    connection_mock = AMock()
    connection_mock.get_url = CoroutineMock(
        return_value=Mock(
            status_code=303, headers=dict(Location="/api/0/DUMMY_LOCATION")
        )
    )
    assert (
        await get_result_location_from_id_when_ready(
            connection=connection_mock, query_id="DUMMY_ID"
        )
        == "DUMMY_LOCATION"
    ) 
Example #7
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_get_status_reports_running(running_status):
    """ Test that status code 202 is interpreted as query running or queued. """
    con_mock = AMock()
    con_mock.get_url = CoroutineMock(
        return_value=Mock(
            status_code=202,
            json=Mock(
                return_value={
                    "status": running_status,
                    "progress": {"eligible": 0, "queued": 0, "running": 0},
                }
            ),
        )
    )
    status = await get_status(connection=con_mock, query_id="foo")
    assert status == running_status 
Example #8
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
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) 
Example #10
Source File: test_logger.py    From aiologger with MIT License 6 votes vote down vote up
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() 
Example #11
Source File: test_async_api_query.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
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" 
Example #12
Source File: test_logger.py    From aiologger with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: test_logger.py    From aiologger with MIT License 6 votes vote down vote up
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() 
Example #14
Source File: test_app.py    From quart with MIT License 6 votes vote down vote up
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 
Example #15
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_get_geography_error(http_code, token):
    """
    Any unexpected http code should raise an exception.
    """
    connection_mock = AMock()
    connection_mock.get_url = CoroutineMock(
        return_value=Mock(
            status_code=http_code, json=Mock(return_value={"msg": "MESSAGE"})
        )
    )
    with pytest.raises(
        FlowclientConnectionError,
        match=f"Could not get result. API returned with status code: {http_code}. Reason: MESSAGE",
    ):
        await get_geography(
            connection=connection_mock, aggregation_unit="DUMMY_AGGREGATION"
        ) 
Example #16
Source File: test_files.py    From aiologger with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: conftest.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #18
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_get_result():
    con_mock = AMock()
    con_mock.post_json = CoroutineMock(
        return_value=Mock(
            status_code=202,
            json=Mock(return_value=dict(msg="DUMMY_ERROR"),),
            headers=dict(Location="DUMMY"),
        ),
    )
    con_mock.get_url = CoroutineMock(
        side_effect=[
            Mock(status_code=303, headers=dict(Location="DUMMY"),),
            Mock(
                status_code=200,
                headers=dict(Location="DUMMY"),
                json=Mock(return_value=dict(query_result=[{"0": 1}])),
            ),
        ]
    )
    assert (
        await get_result(connection=con_mock, query_spec="foo")
    ).values.tolist() == [[1]] 
Example #19
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def test_get_geojson_result():
    con_mock = AMock()
    con_mock.post_json = CoroutineMock(
        return_value=Mock(
            status_code=202,
            json=Mock(return_value=dict(msg="DUMMY_ERROR"),),
            headers=dict(Location="DUMMY"),
        ),
    )
    con_mock.get_url = CoroutineMock(
        side_effect=[
            Mock(status_code=303, headers=dict(Location="DUMMY"),),
            Mock(
                status_code=200,
                headers=dict(Location="DUMMY"),
                json=Mock(return_value=dict(query_result=[{"0": 1}])),
            ),
        ]
    )
    assert (await get_geojson_result(connection=con_mock, query_spec="foo")) == {
        "query_result": [{"0": 1}]
    } 
Example #20
Source File: test_files.py    From aiologger with MIT License 6 votes vote down vote up
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) 
Example #21
Source File: kube_config_test.py    From kubernetes_asyncio with Apache License 2.0 6 votes vote down vote up
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) 
Example #22
Source File: mocking.py    From asynctest with Apache License 2.0 6 votes vote down vote up
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) 
Example #23
Source File: test_async_client.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def test_get_geojson_result_by_query_id_raises(monkeypatch):
    """ Test that get_geojson_result_by_query_id raises an error. """
    con_mock = AMock()
    con_mock.get_url = CoroutineMock(
        return_value=Mock(
            status_code=500, json=Mock(return_value=dict(msg="DUMMY_ERROR"))
        )
    )
    monkeypatch.setattr(
        "flowclient.async_client.get_result_location_from_id_when_ready",
        CoroutineMock(return_value="DUMMY"),
    )
    with pytest.raises(FlowclientConnectionError, match=r".*Reason: DUMMY_ERROR"):
        await get_geojson_result_by_query_id(connection=con_mock, query_id="foo") 
Example #24
Source File: mocking.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_result_with_wrapped_object(self):
        stub = StubClient()
        mock = asynctest.Mock(stub, wraps=stub)
        cache = {}

        stub.add_user(StubClient.User(1, "a.dmin"))
        cache_users(mock, cache)

        mock.get_users.assert_called()
        self.assertEqual(stub.users_to_return, mock.get_users()) 
Example #25
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_with_side_effect_raises_then(self):
        side_effect = asynctest.mock.return_once("ProbeValue", BlockingIOError)
        mock = asynctest.mock.Mock(side_effect=side_effect)
        self.assertEqual("ProbeValue", mock())
        for _ in range(2):
            self.assertRaises(BlockingIOError, mock) 
Example #26
Source File: mocking.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_with_context_manager(self):
        client = asynctest.Mock(AsyncClient())
        cache = {}

        with asynctest.patch("logging.debug") as debug_mock:
            await cache_users_async(client, cache)

        debug_mock.assert_called() 
Example #27
Source File: mocking.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_with_decorator(self, debug_mock, error_mock):
        client = asynctest.Mock(AsyncClient())
        cache = {}

        await cache_users_async(client, cache)

        debug_mock.assert_called()
        error_mock.assert_not_called() 
Example #28
Source File: test_async_api_query.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def test_wait_until_ready(monkeypatch):
    """
    Test that wait_until_ready polls until query_is_ready returns True
    """
    reply_mock = Mock(
        json=Mock(
            return_value={
                "status": "executing",
                "progress": {"eligible": 0, "queued": 0, "running": 0},
            }
        )
    )
    ready_mock = CoroutineMock(side_effect=[(False, reply_mock,), (True, reply_mock),])
    monkeypatch.setattr("flowclient.async_client.query_is_ready", ready_mock)
    connection_mock = AMock()
    connection_mock.post_json = CoroutineMock(
        return_value=Mock(
            status_code=202, headers={"Location": "DUMMY_LOCATION/DUMMY_ID"}
        )
    )
    query = ASyncAPIQuery(
        connection=connection_mock, parameters={"query_kind": "dummy_query"}
    )
    await query.run()
    await query.wait_until_ready()

    assert 2 == ready_mock.call_count 
Example #29
Source File: test_async_api_query.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def test_query_status():
    """
    Test that the 'status' property returns the status reported by the API.
    """
    connection_mock = AMock()
    connection_mock.post_json = CoroutineMock(
        return_value=Mock(
            status_code=202, headers={"Location": "DUMMY_LOCATION/DUMMY_ID"}
        )
    )
    connection_mock.get_url = CoroutineMock(
        return_value=Mock(
            status_code=202,
            json=Mock(
                return_value={
                    "status": "executing",
                    "progress": {"eligible": 0, "queued": 0, "running": 0},
                }
            ),
        )
    )
    query = ASyncAPIQuery(
        connection=connection_mock, parameters={"query_kind": "dummy_query"}
    )
    await query.run()
    assert await query.status == "executing" 
Example #30
Source File: conftest.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def dummy_zmq_server(monkeypatch):
    """
    A fixture which provides a dummy zero mq
    socket which records the json it is asked
    to send and monkeypatches the zmq asyncio context
    to return it.

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

    Yields
    ------
    asynctest.Mock
        The dummy zeromq socket

    """
    dummy = AMock()
    dummy.socket.return_value = dummy

    def f(*args, **kwargs):
        print("Making dummy zmq.")
        return dummy

    monkeypatch.setattr(zmq.asyncio.Context, "instance", f)
    yield dummy