Python asynctest.MagicMock() Examples

The following are 30 code examples of asynctest.MagicMock(). 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_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_mock_aiter_and_anext(self, klass):
        classes = self.get_async_iterator_classes()

        for iterator_class in classes:
            with self.subTest(iterator_class=iterator_class.__name__):
                instance = iterator_class()
                mock_instance = asynctest.MagicMock(instance)

                self.assertEqual(asyncio.iscoroutine(instance.__aiter__),
                                 asyncio.iscoroutine(mock_instance.__aiter__))
                self.assertEqual(asyncio.iscoroutine(instance.__anext__),
                                 asyncio.iscoroutine(mock_instance.__anext__))

                iterator = instance.__aiter__()
                if asyncio.iscoroutine(iterator):
                    iterator = run_coroutine(iterator)

                mock_iterator = mock_instance.__aiter__()
                if asyncio.iscoroutine(mock_iterator):
                    mock_iterator = run_coroutine(mock_iterator)

                self.assertEqual(asyncio.iscoroutine(iterator.__aiter__),
                                 asyncio.iscoroutine(mock_iterator.__aiter__))
                self.assertEqual(asyncio.iscoroutine(iterator.__anext__),
                                 asyncio.iscoroutine(mock_iterator.__anext__)) 
Example #2
Source File: test_openid_connect.py    From python-keycloak-client with MIT License 6 votes vote down vote up
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.client_id = 'client-id'
        self.client_secret = 'client-secret'

        self.openid_client = await KeycloakOpenidConnect(
            realm=self.realm,
            client_id=self.client_id,
            client_secret=self.client_secret
        )
        self.openid_client.well_known.contents = {
            'end_session_endpoint': 'https://logout',
            'jwks_uri': 'https://certs',
            'userinfo_endpoint': 'https://userinfo',
            'authorization_endpoint': 'https://authorization',
            'token_endpoint': 'https://token'
        } 
Example #3
Source File: test_drain_lib.py    From paasta with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: test_decorators.py    From aiocache with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_calls_locked_client(self, decorator, decorator_call):
        decorator.cache.get = CoroutineMock(side_effect=[None, None, None, "value"])
        decorator.cache._add = CoroutineMock(side_effect=[True, ValueError])
        lock1 = MagicMock(spec=RedLock)
        lock2 = MagicMock(spec=RedLock)

        with patch("aiocache.decorators.RedLock", side_effect=[lock1, lock2]):
            await asyncio.gather(decorator_call(value="value"), decorator_call(value="value"))

            assert decorator.cache.get.call_count == 4
            assert lock1.__aenter__.call_count == 1
            assert lock1.__aexit__.call_count == 1
            assert lock2.__aenter__.call_count == 1
            assert lock2.__aexit__.call_count == 1
            decorator.cache.set.assert_called_with(
                "stub()[('value', 'value')]", "value", ttl=SENTINEL
            )
            assert stub.call_count == 1 
Example #5
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 #6
Source File: test_client.py    From python-keycloak-client with MIT License 6 votes vote down vote up
def test_handle_response(self):
        """
        Case: Response get processed
        Expected: Decoded json get returned else raw_response
        """
        req_ctx = asynctest.MagicMock()
        response = req_ctx.__aenter__.return_value
        response.json = asynctest.CoroutineMock()
        response.read = asynctest.CoroutineMock()

        processed_response = await self.client._handle_response(req_ctx)

        response.raise_for_status.assert_called_once_with()
        response.json.assert_awaited_once_with(content_type=None)

        self.assertEqual(processed_response, await response.json())

        response.json.side_effect = ValueError
        processed_response = await self.client._handle_response(req_ctx)

        self.assertEqual(processed_response, await response.read()) 
Example #7
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_mock_supports_async_context_manager(self, klass):
        called = False
        instance = self.WithAsyncContextManager()
        mock_instance = asynctest.mock.MagicMock(instance)

        async def use_context_manager():
            nonlocal called
            async with mock_instance as result:
                called = True

            return result

        result = run_coroutine(use_context_manager())
        self.assertFalse(instance.entered)
        self.assertFalse(instance.exited)
        self.assertTrue(called)
        self.assertTrue(mock_instance.__aenter__.called)
        self.assertTrue(mock_instance.__aexit__.called)
        self.assertIsNot(mock_instance, result)
        self.assertIsInstance(result, asynctest.mock.MagicMock) 
Example #8
Source File: conftest.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def dummy_db_pool(monkeypatch):
    """
    A fixture which provides a mock database connection.

    Yields
    ------
    MagicMock
        The mock db connection that will be used
    """
    dummy = MagicMock()

    # A MagicMock can't be used in an 'await' expression,
    # so we need to make connection.set_type_codec a CoroutineMock
    # (awaited in stream_result_as_json())
    dummy.acquire.return_value.__aenter__.return_value.set_type_codec = CoroutineMock()

    async def f(*args, **kwargs):
        return dummy

    monkeypatch.setattr(asyncpg, "create_pool", f)
    yield dummy 
Example #9
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_mock_customize_async_context_manager_with_coroutine(self, klass):
        enter_called = False
        exit_called = False

        async def enter_coroutine(*args):
            nonlocal enter_called
            enter_called = True

        async def exit_coroutine(*args):
            nonlocal exit_called
            exit_called = True

        instance = self.WithAsyncContextManager()
        mock_instance = asynctest.mock.MagicMock(instance)

        mock_instance.__aenter__ = enter_coroutine
        mock_instance.__aexit__ = exit_coroutine

        async def use_context_manager():
            async with mock_instance:
                pass

        run_coroutine(use_context_manager())
        self.assertTrue(enter_called)
        self.assertTrue(exit_called) 
Example #10
Source File: test_base.py    From aiocache with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_plugins(self):
        self = MagicMock()
        plugin1 = MagicMock()
        plugin1.pre_dummy = CoroutineMock()
        plugin1.post_dummy = CoroutineMock()
        plugin2 = MagicMock()
        plugin2.pre_dummy = CoroutineMock()
        plugin2.post_dummy = CoroutineMock()
        self.plugins = [plugin1, plugin2]

        @API.plugins
        async def dummy(self, *args, **kwargs):
            return True

        assert await dummy(self) is True
        plugin1.pre_dummy.assert_called_with(self)
        plugin1.post_dummy.assert_called_with(self, took=ANY, ret=True)
        plugin2.pre_dummy.assert_called_with(self)
        plugin2.post_dummy.assert_called_with(self, took=ANY, ret=True) 
Example #11
Source File: test_redis.py    From aiocache with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def redis_connection():
    conn = MagicMock()
    conn.__enter__ = MagicMock(return_value=conn)
    conn.__exit__ = MagicMock()
    conn.get = CoroutineMock()
    conn.mget = CoroutineMock()
    conn.set = CoroutineMock()
    conn.setex = CoroutineMock()
    conn.mset = CoroutineMock()
    conn.incrby = CoroutineMock()
    conn.exists = CoroutineMock()
    conn.persist = CoroutineMock()
    conn.expire = CoroutineMock()
    conn.delete = CoroutineMock()
    conn.flushdb = CoroutineMock()
    conn.eval = CoroutineMock()
    conn.keys = CoroutineMock()
    conn.multi_exec = MagicMock(return_value=conn)
    conn.execute = CoroutineMock()
    return conn 
Example #12
Source File: test_client.py    From python-keycloak-client with MIT License 6 votes vote down vote up
def test_delete(self):
        """
        Case: A DELETE request get executed
        Expected: The correct parameters get given to the request library
        """
        self.Session_mock.return_value.headers = asynctest.MagicMock()
        self.Session_mock.return_value.delete = asynctest.CoroutineMock()

        response = await self.client.delete(url='https://example.com/test',
                                            headers={'some': 'header'},
                                            extra='param')

        self.Session_mock.return_value.delete.assert_called_once_with(
            'https://example.com/test',
            headers={'some': 'header'},
            extra='param'
        )
        self.assertEqual(
            response,
            self.Session_mock.return_value.delete.return_value
        ) 
Example #13
Source File: test_client.py    From python-keycloak-client with MIT License 6 votes vote down vote up
def test_put(self):
        """
        Case: A PUT request get executed
        Expected: The correct parameters get given to the request library
        """
        self.Session_mock.return_value.headers = asynctest.MagicMock()

        self.client._handle_response = asynctest.CoroutineMock()
        response = await self.client.put(url='https://example.com/test',
                                         data={'some': 'data'},
                                         headers={'some': 'header'},
                                         extra='param')

        self.Session_mock.return_value.put.assert_called_once_with(
            'https://example.com/test',
            data={'some': 'data'},
            headers={'some': 'header'},
            params={'extra': 'param'}
        )

        self.client._handle_response.assert_awaited_once_with(
            self.Session_mock.return_value.put.return_value
        )
        self.assertEqual(response, self.client._handle_response.return_value) 
Example #14
Source File: test_syncmanager3.py    From neo-python with MIT License 6 votes vote down vote up
def test_headers_received_outdated_height(self):
        # test that a slow response that has been superseeded by a fast response
        # from another node does not get processed twice
        cur_header_height = 1
        node_id = 123

        self.syncmgr.header_request = RequestInfo(cur_header_height + 1)
        self.syncmgr.header_request.add_new_flight(FlightInfo(node_id, cur_header_height + 1))

        height = 2
        header = Header(object(), object(), 0, height, object(), object(), object())

        # mock ledger state
        self.syncmgr.ledger = asynctest.MagicMock()
        self.syncmgr.ledger.cur_header_height = asynctest.CoroutineMock(return_value=2)

        with self.assertLogHandler('syncmanager', DEBUG) as log_context:
            res = await self.syncmgr.on_headers_received(123, [header])
            self.assertEqual(res, -5)
            self.assertGreater(len(log_context.output), 0)
            self.assertTrue("Headers received 2 - 2" in log_context.output[0]) 
Example #15
Source File: test_mock.py    From asynctest with Apache License 2.0 6 votes vote down vote up
def test_patch_as_decorator_uses_MagicMock(self):
        called = []

        @asynctest.mock.patch('test.test_mock.Test')
        def test_mock_class(mock):
            self.assertIsInstance(mock, asynctest.mock.MagicMock)
            called.append("test_mock_class")

        @asynctest.mock.patch('test.test_mock.Test.a_function')
        def test_mock_function(mock):
            self.assertIsInstance(mock, asynctest.mock.MagicMock)
            called.append("test_mock_function")

        test_mock_class()
        test_mock_function()

        self.assertIn("test_mock_class", called)
        self.assertIn("test_mock_function", called) 
Example #16
Source File: test_session.py    From aiozk with MIT License 6 votes vote down vote up
def session(event_loop):
    fake_retry_policy = asynctest.MagicMock(wraps=aiozk.session.RetryPolicy.forever())
    session = aiozk.session.Session(
        'zookeeper.test',
        timeout=10,
        retry_policy=fake_retry_policy,
        allow_read_only=True,
        read_timeout=30,
        loop=asynctest.MagicMock(wraps=event_loop),
    )
    session.state.transition_to(aiozk.session.States.CONNECTED)
    session.conn = asynctest.MagicMock()
    session.conn.send = asynctest.CoroutineMock()
    session.conn.close = asynctest.CoroutineMock()
    session.ensure_safe_state = asynctest.CoroutineMock()
    session.set_heartbeat = mock.Mock()
    return session 
Example #17
Source File: test_redis.py    From aiocache with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def redis_pool(redis_connection):
    class FakePool:
        def __await__(self):
            yield
            return redis_connection

    pool = FakePool()
    pool._conn = redis_connection
    pool.release = CoroutineMock()
    pool.clear = CoroutineMock()
    pool.acquire = CoroutineMock(return_value=redis_connection)
    pool.__call__ = MagicMock(return_value=pool)

    return pool 
Example #18
Source File: test_base.py    From aiocache with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_timeout_self_kwarg(self):
        self = MagicMock()
        self.timeout = 5

        @API.timeout
        async def dummy(self):
            await asyncio.sleep(0.005)

        with pytest.raises(asyncio.TimeoutError):
            await dummy(self, timeout=0.003) 
Example #19
Source File: test_syncmanager3.py    From neo-python with MIT License 5 votes vote down vote up
def setUp(self) -> None:
        # we have to override the singleton behaviour or our coroutine mocks will persist
        with asynctest.patch('neo.Network.syncmanager.SyncManager.__new__', return_value=object.__new__(SyncManager)):
            self.syncmgr = SyncManager()
            self.syncmgr.init(asynctest.MagicMock)
            self.syncmgr.reset() 
Example #20
Source File: test_client.py    From python-keycloak-client with MIT License 5 votes vote down vote up
def test_post(self):
        """
        Case: A POST request get executed
        Expected: The correct parameters get given to the request library
        """
        self.Session_mock.return_value.headers = asynctest.MagicMock()

        self.client._handle_response = asynctest.CoroutineMock()
        response = await self.client.post(
            url='https://example.com/test',
            data={'some': 'data'},
            headers={'some': 'header'},
            extra='param'
        )

        self.Session_mock.return_value.post.assert_called_once_with(
            'https://example.com/test',
            data={'some': 'data'},
            headers={'some': 'header'},
            params={'extra': 'param'}
        )

        self.client._handle_response.assert_awaited_once_with(
            self.Session_mock.return_value.post.return_value
        )
        self.assertEqual(response, self.client._handle_response.return_value) 
Example #21
Source File: test_uma.py    From python-keycloak-client with MIT License 5 votes vote down vote up
def setUp(self):
        self.realm = asynctest.MagicMock(spec_set=KeycloakRealm)
        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.uma_client = await KeycloakUMA(realm=self.realm)
        self.uma_client.well_known.contents = {
            'resource_registration_endpoint': 'https://resource_registration',
            'permission_endpoint': 'https://permission',
            'policy_endpoint': 'https://policy',
        } 
Example #22
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_with_MagicMock(self):
        default = asynctest.mock.DEFAULT
        with asynctest.mock.patch.multiple('test.test_mock', Test=default):
            import test.test_mock
            self.assertIsInstance(test.test_mock.Test, asynctest.mock.MagicMock) 
Example #23
Source File: test_authz.py    From python-keycloak-client with MIT License 5 votes vote down vote up
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.realm_name = 'realm-name'
        self.client_id = 'client-id'
        self.authz = await KeycloakAuthz(realm=self.realm,
                                         client_id=self.client_id) 
Example #24
Source File: test_roles.py    From python-keycloak-client with MIT License 5 votes vote down vote up
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') 
Example #25
Source File: test_users.py    From python-keycloak-client with MIT License 5 votes vote down vote up
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') 
Example #26
Source File: mocking.py    From asynctest with Apache License 2.0 5 votes vote down vote up
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)
        self.assertEqual(nb_added, 0)
        self.assertEqual(cache[1], user) 
Example #27
Source File: mocking.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_iterable(self):
        loop_iterations = 0
        mock = asynctest.MagicMock()
        mock.__aiter__.return_value = range(5)
        async for _ in mock:
            loop_iterations += 1

        self.assertEqual(5, loop_iterations) 
Example #28
Source File: mocking.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_context_manager(self):
        with self.assertRaises(AssertionError):
            async with asynctest.MagicMock() as context:
                # context is a MagicMock
                context.assert_called() 
Example #29
Source File: test_mock.py    From asynctest with Apache License 2.0 5 votes vote down vote up
def test_patch_coroutine_function_with_CoroutineMock(self):
        default = asynctest.mock.DEFAULT

        with asynctest.mock.patch.multiple('test.test_mock.Test',
                                           a_function=default,
                                           a_coroutine=default,
                                           an_async_coroutine=default):
            import test.test_mock
            obj = test.test_mock.Test()
            self.assertIsInstance(obj.a_function, asynctest.mock.MagicMock)
            self.assertIsInstance(obj.a_coroutine, asynctest.mock.CoroutineMock)
            self.assertIsInstance(obj.an_async_coroutine, asynctest.mock.CoroutineMock) 
Example #30
Source File: test_syncmanager2.py    From neo-python with MIT License 5 votes vote down vote up
def test_outstanding_header_request_timedout_but_received(self):
        """
        test an outstanding request that timedout, but has been received in the meantime
        """
        cur_header_height = 1
        node_id = 123

        # mock node manager state
        self.syncmgr.nodemgr = asynctest.MagicMock()
        node1 = NeoNode(object(), object())
        node1.nodeid = node_id
        self.syncmgr.nodemgr.get_node_by_id.return_value = node1

        # mock ledger state
        self.syncmgr.ledger = asynctest.MagicMock()
        # we pretend our local ledger has a height higher than what we just asked for
        self.syncmgr.ledger.cur_header_height = asynctest.CoroutineMock(return_value=3)

        # setup sync manager state to have an outstanding header request
        self.syncmgr.header_request = RequestInfo(cur_header_height + 1)
        fi = FlightInfo(node_id, cur_header_height + 1)
        fi.start_time = fi.start_time - 5  # decrease start time by 5 seconds to exceed timeout threshold
        self.syncmgr.header_request.add_new_flight(fi)

        with self.assertLogHandler('syncmanager', DEBUG) as log_context:
            await self.syncmgr.check_timeout()
            self.assertGreater(len(log_context.output), 0)
            self.assertTrue("Header timeout limit exceed" in log_context.output[0])

        self.assertIsNone(self.syncmgr.header_request)