Exemple #1
0
async def update_coro(sess: aiohttp.ClientSession, addrs: Tuple[str, str],
                      skus: List[str]) -> Coroutine:
    """Update tags
    """
    try:
        pull_data_url = urllib.parse.urljoin(addrs[0], _config.PRODUCT_API)
        push_data_url = urllib.parse.urljoin(addrs[1],
                                             _config.ELS_UPDATE_PRODUCT_API)
        p_res = await sess.get(pull_data_url,
                               params=_make_pull_product_request(skus))
        data = await p_res.json()
        if p_res.status != 200:
            raise aiohttp.ClientPayloadError(
                f"Call product server: {data['message']}")
        els_res = await sess.post(push_data_url,
                                  json=_make_push_product_request(
                                      data['result']['products'], skus))
        data = await els_res.json()
        if els_res.status != 200:
            raise aiohttp.ClientError(f"Call els server: {data['ERROR']}")
    except aiohttp.ClientError as err:
        logging.error(str(err))
    else:
        logging.info('Push data success')
        logging.info(data)
    async def test_fetch_with_empty_client_error(self, mocked_post):
        """Test fetching measurement when getting measurements fails with an 'empty' exception.

        This can happen when an exception returns an empty string when converted to string.
        """
        mock_async_get_request = AsyncMock()
        mock_async_get_request.close = Mock()
        mock_async_get_request.json.return_value = self.metrics
        await self.fetch_measurements(None, side_effect=[mock_async_get_request, aiohttp.ClientPayloadError()])
        mocked_post.assert_called_once_with(
            self.measurement_api_url,
            json=dict(
                sources=[
                    dict(
                        api_url=self.url,
                        landing_url=self.url,
                        value=None,
                        total=None,
                        entities=[],
                        connection_error="ClientPayloadError",
                        parse_error=None,
                        source_uuid="source_id",
                    )
                ],
                metric_uuid="metric_uuid",
            ),
        )
Exemple #3
0
    async def _extract_response_data(
        resp: aiohttp.ClientResponse,
    ) -> list | dict:
        """Checks the correctness of the response.

        Args:
            resp: Response instance.

        Returns:
            resp['data'] field if expected data.

        Raises:
            aiohttp.ClientResponseError: if response status >= 400.
            aiohttp.ClientPayloadError: if failure result of the request.

            #TODO: refactor for process HTTP statuses!
        """
        resp.raise_for_status()

        json = await resp.json()
        if json.get("success"):
            _LOG.debug(
                "Successfully response",
                extra={
                    "url": resp.url,
                },
            )
            return json.get("data", {})
        raise aiohttp.ClientPayloadError(f"Failure server result: {resp.url} {json}")
Exemple #4
0
def test_poller_negative():
    task = {'url': 'test_url'}

    loop = asyncio.get_event_loop()
    with aioresponses() as mock:
        mock.get('test_url',
                 status=200,
                 exception=aiohttp.ClientPayloadError('test_msg'))

        result = loop.run_until_complete(AsyncSitePoller().process(task))
        assert not result['success'], 'success must be False'
        assert 'ClientPayloadError' in result['error_type']
        assert result['message'] == 'test_msg'
    async def test_stream(self, mock_stream):
        mock_stream.return_value = stream_data
        mock_stream_response = MockStreamResponse(200)
        # fake stop event
        self.sse_client.stop_event = asyncio.Event()
        self.sse_client.stop_event.set()
        # mock the fire events function
        with asynctest.patch.object(CrownstoneSSE,
                                    'fire_events') as fire_event_mock:
            await self.sse_client.stream(mock_stream_response)

        # test if data correctly received and parsed
        fire_event_mock.assert_called_once_with({
            'type': 'testType',
            'subType': 'testSubType'
        })

        # test no data available
        mock_stream_response = MockStreamResponse(204)
        with asynctest.patch.object(CrownstoneSSE,
                                    'fire_events') as fire_event_mock:
            await self.sse_client.stream(mock_stream_response)

        # test if fire events is not called this time
        fire_event_mock.assert_not_called()

        # mock token expired
        mock_stream.return_value = token_expired_data
        mock_stream_response = MockStreamResponse(200)
        with asynctest.patch.object(CrownstoneSSE,
                                    'refresh_token') as refresh_mock:
            await self.sse_client.stream(mock_stream_response)

        # test refresh call
        refresh_mock.assert_called_once()

        # mock connect function
        mock_stream.side_effect = aiohttp.ClientPayloadError('test')
        with asynctest.patch.object(CrownstoneSSE, 'connect') as connect_mock:
            await self.sse_client.stream(mock_stream_response)

        # test if reconnect called
        connect_mock.assert_called_once()