diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index 839dc397780f..1edb806a043c 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -16,6 +16,7 @@ Azure-core is supported on Python 3.7 or later. For more details, please read ou ### Features Added +- Added **experimental** Pyodide-compatible transport. - Added `CaseInsensitiveDict` implementation in `azure.core.utils` removing dependency on `requests` and `aiohttp` ## 1.24.2 (2022-06-30) diff --git a/sdk/core/azure-core/azure/core/pipeline/transport/__init__.py b/sdk/core/azure-core/azure/core/pipeline/transport/__init__.py index 7db60657284b..ca7ef21340a7 100644 --- a/sdk/core/azure-core/azure/core/pipeline/transport/__init__.py +++ b/sdk/core/azure-core/azure/core/pipeline/transport/__init__.py @@ -43,6 +43,8 @@ 'TrioRequestsTransportResponse', 'AioHttpTransport', 'AioHttpTransportResponse', + 'PyodideTransport', + 'PyodideTransportResponse', ] # pylint: disable=unused-import, redefined-outer-name, no-member, too-many-statements, too-many-branches @@ -102,6 +104,18 @@ def __getattr__(name): transport = TrioRequestsTransportResponse except ImportError: raise ImportError("trio package is not installed") + if name == 'PyodideTransport': + try: + from ._pyodide import PyodideTransport + transport = PyodideTransport + except ImportError: + raise ImportError("pyodide package is not installed") + if name == 'PyodideTransportResponse': + try: + from ._pyodide import PyodideTransportResponse + transport = PyodideTransportResponse + except ImportError: + raise ImportError("pyodide package is not installed") if transport: return transport raise AttributeError(f"module 'azure.core.pipeline.transport' has no attribute {name}") diff --git a/sdk/core/azure-core/samples/pyodide_integration/async_testing.py b/sdk/core/azure-core/samples/pyodide_integration/async_testing.py new file mode 100644 index 000000000000..1e3eff2f9901 --- /dev/null +++ b/sdk/core/azure-core/samples/pyodide_integration/async_testing.py @@ -0,0 +1,27 @@ +import traceback +import sys + + +class AsyncTestSuite: + """Async test cases + Test must be asynchronous and follow the pattern `test*`. + """ + + async def run(self): + """Run the tests an print the results.""" + print("".join(("-" * 8, type(self).__name__, "-" * 8))) + for method_name in dir(self): + if not method_name.startswith("test"): + continue + print(method_name, end="... ") + try: + await getattr(self, method_name)() + except AssertionError: + print("FAIL") + traceback.print_exception(*sys.exc_info()) + except Exception: # pylint: disable=broad-except + print("ERROR") + traceback.print_exception(*sys.exc_info()) + else: + print("PASS") + print() diff --git a/sdk/core/azure-core/samples/pyodide_integration/browser.py b/sdk/core/azure-core/samples/pyodide_integration/browser.py new file mode 100644 index 000000000000..80578d5c5571 --- /dev/null +++ b/sdk/core/azure-core/samples/pyodide_integration/browser.py @@ -0,0 +1,104 @@ +from unittest.mock import _patch_dict, patch +from uuid import uuid4 + +from azure.ai.textanalytics.aio import TextAnalyticsClient +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline.transport import HttpRequest, PyodideTransport +from azure.storage.blob.aio import BlobClient, BlobServiceClient + +# pylint: disable=import-error +from async_testing import AsyncTestSuite + + +class PyodideTransportIntegrationTestSuite(AsyncTestSuite): + """Integration tests for the Pyodide transport.""" + + text_analytics_client: TextAnalyticsClient + blob_service_client: BlobServiceClient + + def __init__( + self, + text_analytics_key: str, + text_analytics_endpoint: str, + blob_service_key: str, + blob_service_endpoint: str, + ): + self.text_analytics_client = TextAnalyticsClient( + endpoint=text_analytics_endpoint, + credential=AzureKeyCredential(text_analytics_key), + transport=PyodideTransport(), + ) + self.blob_service_client = BlobServiceClient( + blob_service_endpoint, blob_service_key, transport=PyodideTransport() + ) + + async def test_decompress_generator(self): + """Test that we can decompress streams properly.""" + url = "data/hello-world.gz" + request = HttpRequest(method="GET", url=url) + transport = PyodideTransport() + response = await transport.send(request, stream_response=True) + response.headers["enc"] = "deflate" + data = b"".join([x async for x in response.iter_bytes()]) + assert data == b"hello world\n" + + response = await transport.send(request, stream_response=True) + data = b"".join([x async for x in response.iter_raw()]) + assert data != b"hello world\n" + + response = await transport.send(request, stream_response=True) + data = b"".join([x async for x in response.iter_bytes()]) + assert data != b"hello world\n" + + response = await transport.send(request, stream_response=True) + response.headers["enc"] = "deflate" + data = b"".join([x async for x in response.iter_bytes()]) + assert data == b"hello world\n" + + + async def test_sentiment_analysis(self): + """Test that sentiment analysis works.""" + results = await self.text_analytics_client.analyze_sentiment( + ["good great amazing"] + ) + assert len(results) == 1 + result = results[0] + assert result.sentiment == "positive" + assert result.confidence_scores.positive > 0.98 + assert result.confidence_scores.neutral < 0.02 + assert result.confidence_scores.negative < 0.02 + + async def test_storage(self): + """Test that we can upload and download from blob storage""" + account_name = uuid4().hex + container_client = await self.blob_service_client.create_container(account_name) + blob_name = uuid4().hex + blob_data = b"012345" + try: + assert await container_client.exists() + blob_client = container_client.get_blob_client(blob_name) + await blob_client.upload_blob(blob_data) + + # make a new client so we don't have cached data + blob_client = BlobClient( + account_url=self.blob_service_client.url, + container_name=container_client.container_name, + blob_name=blob_name, + credential=container_client.credential, + max_single_get_size=1, + max_chunk_get_size=1, + transport=PyodideTransport(), + ) + assert await blob_client.exists() + downloader = await blob_client.download_blob() + i = 0 + async for chunk in downloader.chunks(): + assert chunk == bytes(str(i), "utf-8") + i += 1 + assert i == len(blob_data) + + except Exception: + await container_client.delete_container() + raise + else: + await container_client.delete_container() diff --git a/sdk/core/azure-core/samples/pyodide_integration/data/hello-world.gz b/sdk/core/azure-core/samples/pyodide_integration/data/hello-world.gz new file mode 100644 index 000000000000..34336ab5dd95 Binary files /dev/null and b/sdk/core/azure-core/samples/pyodide_integration/data/hello-world.gz differ diff --git a/sdk/core/azure-core/samples/pyodide_integration/example-env b/sdk/core/azure-core/samples/pyodide_integration/example-env new file mode 100644 index 000000000000..57f925f76d42 --- /dev/null +++ b/sdk/core/azure-core/samples/pyodide_integration/example-env @@ -0,0 +1,4 @@ +TEXT_ANALYTICS_KEY= +TEXT_ANALYTICS_ENDPOINT= +BLOB_SERVICE_KEY= +BLOB_SERVICE_ENDPOINT=https://.blob.core.windows.net diff --git a/sdk/core/azure-core/samples/pyodide_integration/index.html b/sdk/core/azure-core/samples/pyodide_integration/index.html new file mode 100644 index 000000000000..9391e05df16a --- /dev/null +++ b/sdk/core/azure-core/samples/pyodide_integration/index.html @@ -0,0 +1,89 @@ + + + + + + + + + + diff --git a/sdk/core/azure-core/samples/pyodide_integration/readme.md b/sdk/core/azure-core/samples/pyodide_integration/readme.md new file mode 100644 index 000000000000..939fecdfc05a --- /dev/null +++ b/sdk/core/azure-core/samples/pyodide_integration/readme.md @@ -0,0 +1,43 @@ +# Integration Testing + +## Running + +Once you have set up your Azure Resources and your `.env` file, navigate to the `/sdk/core/azure-core`. Make a wheel of core by running + +```bash +python setup.py bdist_wheel +``` + +and run + +```python +python -h http.server +``` + +to set up the test server. Then, from a Chromium-based browser such as Edge, go to [`http://localhost:8000/samples/pyodide_integration`](http://localhost:8000/samples/test_pyodide_integration) and the tests will be run in the browser. Dev tip: keep your browser's devtools open. If you make a change to the source code, remember to rebuild your wheel. Note that you might have to update `requirements.txt` depending on the version of `azure-core`. Just make sure the url to `azure-core` in `requirements.txt` matches that of the wheel in `../../dist/`. + +## Adding tests + +Add tests in `browser_test.py`. I couldn't get `pytest` or `unittest` to cooperate with me, so I made my own little async testing framework (`async_test.py`). If you are creating new files to test or new packages, update the `TEST_FILES` and `PACKAGES` variables in `index.html`, import the test case, and run it. + +## Sensitive values + +To run the tests, you need a `.env` folder in this directory with your sensitive values. +see `example-env`. You can then access the values as environment variables using `os.getenv`. You will +need to have your `textanalytics` key and endpoint as well as your Blob Storage key and url. + +## Dependencies + +All all packages listed in `requirements.txt` will be available in the testing environment. + +## Azure Resources + +You need your own Text Analytics and Blob Storage accounts to run these tests. Blob storage requirest some additional configuration to work. To set up Blob Storage, navigate to your storage client homepage and go to the `Resource Sharing (CORS)` tab. Create a rule with the following values + +| Allowed origins | Allowed methods | Allowed headers | Exposed headers | Max age | +|-----------------|-----------------|-----------------|-----------------|---------| +| `*` | All | `*` | See below | `3600` | + +For exposed headers, put + +> Server,Content-Range,ETag,Last-Modified,Accept-Ranges,x-ms-*,enc diff --git a/sdk/core/azure-core/samples/pyodide_integration/requirements.txt b/sdk/core/azure-core/samples/pyodide_integration/requirements.txt new file mode 100644 index 000000000000..97135659a4df --- /dev/null +++ b/sdk/core/azure-core/samples/pyodide_integration/requirements.txt @@ -0,0 +1,5 @@ +python-dotenv +http://localhost:8000/dist/azure_core-1.25.0-py3-none-any.whl +azure-ai-textanalytics +azure-storage-blob +azure-ai-formrecognizer diff --git a/sdk/core/azure-core/tests/test_pyodide_transport.py b/sdk/core/azure-core/tests/test_pyodide_transport.py new file mode 100644 index 000000000000..e7abb2800979 --- /dev/null +++ b/sdk/core/azure-core/tests/test_pyodide_transport.py @@ -0,0 +1,222 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# -------------------------------------------------------------------------- +"""Tests that mock the browser layer.""" +import asyncio +import sys +from typing import NamedTuple +from unittest import mock + +import pytest +from azure.core.exceptions import HttpResponseError +from azure.core.pipeline._base_async import AsyncPipeline +from azure.core.pipeline.policies._retry_async import AsyncRetryPolicy +from azure.core.rest import HttpRequest + +PLACEHOLDER_ENDPOINT = "https://my-resource-group.cognitiveservices.azure.com/" + + +class TestPyodideTransportClass: + """Unittest for the Pyodide transport.""" + + @pytest.fixture() + def mock_pyodide_module(self): + """Create a mock for the Pyodide module.""" + mock_pyodide_module = mock.Mock() + mock_pyodide_module.http.pyfetch = mock.Mock() + mock_pyodide_module.JsException = type("JsException", (Exception,), {}) + return mock_pyodide_module + + @pytest.fixture() + def mock_js_module(self): + """Mock the `js` module""" + return mock.Mock() + + @pytest.fixture() + def transport(self, mock_pyodide_module, mock_js_module): + """Add the mock Pyodide module to `sys.modules` and import our transport.""" + # Use patch so we don't clutter up the `sys.modules` namespace. + patch_dict = ( + ("pyodide", mock_pyodide_module), + ("pyodide.http", mock_pyodide_module.http), + ("js", mock_js_module), + ) + with mock.patch.dict(sys.modules, patch_dict): + import azure.core.pipeline.transport + + yield azure.core.pipeline.transport + + @pytest.fixture() + def pipeline(self, transport): + """Create a pipeline to test.""" + return AsyncPipeline(transport.PyodideTransport(), [AsyncRetryPolicy()]) + + @pytest.fixture() + def mock_pyfetch(self, mock_pyodide_module): + """Utility fixture for less typing.""" + return mock_pyodide_module.http.pyfetch + + def create_mock_response( + self, body: bytes, headers: dict, status: int, status_text: str + ) -> mock.Mock: + """Create a mock response object that mimics `pyodide.http.FetchResponse`""" + mock_response = mock.Mock() + mock_response.body = body + mock_response.js_response.headers = headers + mock_response.status = status + mock_response.status_text = status_text + bytes_promise = asyncio.Future() + bytes_promise.set_result(body) + mock_response.bytes = mock.Mock() + mock_response.bytes.return_value = bytes_promise + mock_response.clone.return_value = mock_response + + response_promise = asyncio.Future() + response_promise.set_result(mock_response) + return response_promise + + @pytest.mark.asyncio + async def test_successful_send(self, mock_pyfetch, mock_pyodide_module, pipeline): + """Test that a successful send returns the correct values.""" + # setup data + mock_pyfetch.reset_mock() + method = "POST" + headers = {"key": "value"} + data = b"data" + request = HttpRequest( + method=method, url=PLACEHOLDER_ENDPOINT, headers=headers, data=data + ) + response_body = b"0123" + response_headers = {"header": "value"} + response_status = 200 + response_text = "OK" + mock_response = self.create_mock_response( + body=response_body, + headers=response_headers, + status=response_status, + status_text=response_text, + ) + mock_pyodide_module.http.pyfetch.return_value = mock_response + response = (await pipeline.run(request=request)).http_response + # Check that the pipeline processed the data correctly. + await response.load_body() + assert response.body() == response_body + assert response.status_code == response_status + assert response.headers == response_headers + assert response.reason == response_text + + assert not response._is_closed + await response.close() + assert response._is_closed + + # Check that the call had the correct arguments. + mock_pyfetch.assert_called_once() + args = mock_pyfetch.call_args[0] + kwargs = mock_pyfetch.call_args[1] + assert len(args) == 1 + assert args[0] == PLACEHOLDER_ENDPOINT + assert kwargs["method"] == method + assert kwargs["body"] == data + assert not kwargs["allow_redirects"] + assert kwargs["headers"]["key"] == "value" + assert kwargs["headers"]["Content-Length"] == str(len(data)) + assert kwargs["verify"] + assert kwargs["cert"] is None + assert not kwargs["files"] + + # check that the js_stream property is cloning + num_clones = mock_pyfetch.clone.call_count + response.js_stream + assert mock_pyfetch.call_count == num_clones + 1 + + + @pytest.mark.asyncio + async def test_unsuccessful_send(self, mock_pyfetch, mock_pyodide_module, pipeline): + """Test that the pipeline is failing correctly.""" + mock_pyfetch.reset_mock() + mock_pyfetch.side_effect = mock_pyodide_module.JsException + retry_total = 3 + request = HttpRequest(method="GET", url=PLACEHOLDER_ENDPOINT) + with pytest.raises(HttpResponseError): + await pipeline.run(request) + # 3 retries plus the original request. + assert mock_pyfetch.call_count == retry_total + 1 + + @pytest.mark.asyncio + async def test_download_generator(self, transport): + """Test that the download generator is working correctly.""" + class ReaderReturn(NamedTuple): + value: bytes + done: bool + + response_mock = mock.Mock() + response_mock._block_size = 5 + response_mock._js_reader.read = mock.Mock() + read_promise = asyncio.Future() + read_promise.set_result(ReaderReturn(value=b"01", done=False)) + reader = mock.Mock() + reader.read.return_value = read_promise + response_mock.js_stream.getReader.return_value = reader + generator = transport.PyodideStreamDownloadGenerator(pipeline=None, response=response_mock) + + assert len(await generator.__anext__()) == response_mock._block_size + assert reader.read.call_count == 3 + assert len(await generator.__anext__()) == response_mock._block_size + # 5 because there is a leftover byte from the previous `__anext__` call. + assert reader.read.call_count == 5 + + read_promise = asyncio.Future() + read_promise.set_result(ReaderReturn(value=None, done=True)) + reader.read.return_value = read_promise + await generator.__anext__() + with pytest.raises(StopAsyncIteration): + await generator.__anext__() + + @pytest.mark.asyncio + async def test_download_generator_compress(self, transport, mock_js_module): + """Test that we are attempting to decompress data when passing the `decompress`.""" + response = mock.Mock() + response.headers = {"enc": "deflate"} + transport.PyodideStreamDownloadGenerator(pipeline=None, response=response, decompress=True) + mock_js_module.DecompressionStream.new.assert_called_once_with("gzip") + + def test_valid_import(self, transport): + """Test that we can import Pyodide classes from `azure.core.pipeline.transport` + Adding the transport fixture will mock the Pyodide modules in `sys.modules`. + """ + # Use patch so we don't clutter up the `sys.modules` namespace. + import azure.core.pipeline.transport as transport + assert transport.PyodideTransport + assert transport.PyodideTransportResponse + + def test_invalid_import(self): + """Test that correct errors are thrown when importing Pyodide class in the wrong + context. + """ + import azure.core.pipeline.transport as transport + with pytest.raises(ImportError): + transport.PyodideTransport + with pytest.raises(ImportError): + transport.PyodideTransportResponse