How to use the asynctest.MagicMock function in asynctest

To help you get started, we’ve selected a few asynctest examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github home-assistant / home-assistant / tests / components / ness_alarm / test_init.py View on Github external
def mock_nessclient():
    """Mock the nessclient Client constructor.

    Replaces nessclient.Client with a Mock which always returns the same
    MagicMock() instance.
    """
    _mock_instance = MagicMock(MockClient())
    _mock_factory = MagicMock()
    _mock_factory.return_value = _mock_instance

    with MockDependency("nessclient"), patch(
        "nessclient.Client", new=_mock_factory, create=True
    ), patch("nessclient.ArmingState", new=MockArmingState):
        yield _mock_instance
github Yelp / paasta / tests / test_drain_lib.py View on Github external
async def test_is_draining_yes(self):
        fake_response = mock.Mock(
            status=503,
            text=asynctest.CoroutineMock(
                return_value="Service service in down state since 1435694078.778886 "
                "until 1435694178.780000: Drained by Paasta"
            ),
        )
        fake_task = mock.Mock(host="fake_host", ports=[54321])
        with mock_ClientSession(
            get=mock.Mock(
                return_value=asynctest.MagicMock(
                    __aenter__=asynctest.CoroutineMock(return_value=fake_response)
                )
            )
        ):
            assert await self.drain_method.is_draining(fake_task) is True
github futuresimple / triggear / tests / github_controller / test_hook.py View on Github external
async def test_handling_push(gh_sut: GithubController):
    with asynctest.patch.object(gh_sut, 'get_request_json',
                                return_value={'action': 'not_matched', 'ref': 'refs/heads/master'}):
        with asynctest.patch.object(gh_sut, 'validate_webhook_secret', return_value='AUTHORIZED'):
            with asynctest.patch.object(gh_sut, 'get_request_event_header', return_value='push'):
                with asynctest.patch.object(gh_sut, 'handle_push') as handle_mock:
                    result = await gh_sut.handle_hook(asynctest.MagicMock())
                    assert result.status == 200
                    handle_mock.assert_called_once_with({'action': 'not_matched', 'ref': 'refs/heads/master'})
github Peter-Slump / python-keycloak-client / tests / keycloak / aio / admin / test_users.py View on Github external
def setUp(self):
        self.realm = asynctest.MagicMock(spec_set=KeycloakRealm)
        self.realm.client = asynctest.MagicMock(spec_set=KeycloakClient)()
        self.realm.client.get = asynctest.CoroutineMock()
        self.realm.client.post = asynctest.CoroutineMock()
        self.realm.client.put = asynctest.CoroutineMock()
        self.realm.client.delete = asynctest.CoroutineMock()
        self.admin = KeycloakAdmin(realm=self.realm)
        self.admin.set_token('some-token')
github ShorensteinCenter / Benchmarks-Program / tests / unit / test_lists.py View on Github external
async def test_make_async_requests(mocker, mailchimp_list):
    """Tests the make_async_requests function."""
    semaphore_mock = asynctest.MagicMock()
    mocked_make_async_request = mocker.patch(
        'app.lists.MailChimpList.make_async_request', new=CoroutineMock())
    mocked_make_async_request.return_value = '["foo"]'
    assert ['foo'] == await mailchimp_list.make_async_requests(
        semaphore_mock, 'www.foo.com', 'foo', 'bar')
    mocked_make_async_request.assert_called_with(
        'www.foo.com', 'foo', 'bar')
github Peter-Slump / python-keycloak-client / tests / keycloak / aio / admin / test_roles.py View on Github external
def setUp(self):
        self.realm = asynctest.MagicMock(spec_set=KeycloakRealm)
        self.realm.client = asynctest.MagicMock(spec_set=KeycloakClient)()
        self.realm.client.get = asynctest.CoroutineMock()
        self.realm.client.post = asynctest.CoroutineMock()
        self.realm.client.put = asynctest.CoroutineMock()
        self.realm.client.delete = asynctest.CoroutineMock()
        self.realm.realm_name = 'realm-name'
        self.client_id = 'client-id'
        self.admin = KeycloakAdmin(realm=self.realm)
        self.admin.set_token('some-token')
github opsdroid / opsdroid / tests / test_connector_websocket.py View on Github external
async def test_websocket_handler(self):
        """Test the websocket handler."""
        import aiohttp
        from datetime import datetime, timedelta

        connector = ConnectorWebsocket({}, opsdroid=OpsDroid())
        room = "a146f52c-548a-11e8-a7d1-28cfe949e12d"
        mock_request = amock.Mock()
        mock_request.match_info = amock.Mock()
        mock_request.match_info.get = amock.Mock()
        mock_request.match_info.get.return_value = room
        connector.available_connections = [{"id": room, "date": datetime.now()}]

        with OpsDroid() as opsdroid, amock.patch(
            "aiohttp.web.WebSocketResponse", new=asynctest.MagicMock()
        ) as mock_WebSocketResponse:
            connector.opsdroid = opsdroid
            connector.opsdroid.parse = amock.CoroutineMock()
            mock_socket = asynctest.MagicMock()
            mock_socket.prepare = amock.CoroutineMock()
            mock_socket.exception = amock.CoroutineMock()
            socket_message_1 = amock.CoroutineMock()
            socket_message_1.type = aiohttp.WSMsgType.TEXT
            socket_message_1.data = "Hello world!"
            socket_message_2 = amock.CoroutineMock()
            socket_message_2.type = aiohttp.WSMsgType.ERROR
            socket_message_2.data = "Error!"
            mock_socket.__aiter__.return_value = [socket_message_1, socket_message_2]
            mock_WebSocketResponse.return_value = mock_socket
            response = await connector.websocket_handler(mock_request)
            self.assertEqual(response, mock_socket)
github zalando-incubator / kopf / tests / invocations / test_callbacks.py View on Github external
async def test_result_returned(fn):
    fn = MagicMock(fn, return_value=999)
    result = await invoke(fn)
    assert result == 999
github Martiusweb / asynctest / doc / examples / tutorial / mocking.py View on Github external
async def test_one_user_added_to_cache(self):
        user = StubClient.User(1, "a.dmin")

        AsyncClientMock = asynctest.create_autospec(AsyncClient)

        transaction = asynctest.MagicMock()
        transaction.__aenter__.side_effect = AsyncClientMock

        cursor = asynctest.MagicMock()
        cursor.__aiter__.return_value = [user]

        client = AsyncClientMock()
        client.new_transaction.return_value = transaction
        client.get_users_cursor.return_value = cursor

        cache = {}

        # The user has been added to the cache
        nb_added = await cache_users_with_cursor(client, cache)

        self.assertEqual(nb_added, 1)
        self.assertEqual(cache[1], user)

        # The user was already there
        nb_added = await cache_users_with_cursor(client, cache)
github Yelp / paasta / tests / test_hacheck.py View on Github external
async def test_get_spool():
    fake_response = mock.Mock(
        status=503,
        text=asynctest.CoroutineMock(
            return_value="Service service in down state since 1435694078.778886 "
            "until 1435694178.780000: Drained by Paasta"
        ),
    )
    fake_task = mock.Mock(host="fake_host", ports=[54321])

    with mock_ClientSession(
        get=asynctest.Mock(
            return_value=asynctest.MagicMock(
                __aenter__=asynctest.CoroutineMock(return_value=fake_response)
            )
        )
    ):
        actual = await hacheck.get_spool(fake_task)

    expected = {
        "service": "service",
        "state": "down",
        "reason": "Drained by Paasta",
        "since": 1435694078.778886,
        "until": 1435694178.780000,
    }
    assert actual == expected