Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .vscode/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,13 @@
"Phong"
]
},
{
"filename": "sdk/core/azure-core/tests/test_serialization.py",
"words": [
"Rlcw",
"Jwcmlud"
]
},
{
"filename": "sdk/tables/azure-data-tables/tests/**/*.py",
"words": [
Expand Down
2 changes: 1 addition & 1 deletion sdk/core/azure-core-experimental/azure/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
2 changes: 1 addition & 1 deletion sdk/core/azure-core-experimental/azure/core/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@
# --------------------------------------------------------------------------

from ._version import VERSION

__version__ = VERSION
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,17 @@

if sys.version_info >= (3, 7):
__all__ = [
'PyodideTransport',
"PyodideTransport",
]

def __dir__():
return __all__

def __getattr__(name):
if name == 'PyodideTransport':
if name == "PyodideTransport":
try:
from ._pyodide import PyodideTransport

return PyodideTransport
except ImportError:
raise ImportError("pyodide package is not installed")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from collections.abc import AsyncIterator
from io import BytesIO

import js # pylint: disable=import-error
import js # pylint: disable=import-error
from pyodide import JsException # pylint: disable=import-error
from pyodide.http import pyfetch # pylint: disable=import-error

Expand All @@ -42,7 +42,6 @@
class PyodideTransportResponse(AsyncHttpResponseImpl):
"""Async response object for the `PyodideTransport`."""


def _js_stream(self):
"""So we get a fresh stream every time."""
return self._internal_response.clone().js_response.body
Expand All @@ -62,6 +61,7 @@ async def load_body(self) -> None:
if self._content is None:
self._content = await self._internal_response.clone().bytes()


class PyodideStreamDownloadGenerator(AsyncIterator):
"""Simple stream download generator that returns the contents of
a request.
Expand Down Expand Up @@ -106,6 +106,7 @@ async def __anext__(self) -> bytes:
self._buffer_left -= self._block_size
return self._stream.read(self._block_size)


class PyodideTransport(AsyncioRequestsTransport):
"""**This object is experimental**, meaning it may be changed in a future release
or might break with a future Pyodide release. This transport was built with Pyodide
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,9 @@ async def test_decompress_generator(self):
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"]
)
results = await self.text_analytics_client.analyze_sentiment(["good great amazing"])
assert len(results) == 1
result = results[0]
assert result.sentiment == "positive"
Expand Down
53 changes: 26 additions & 27 deletions sdk/core/azure-core-experimental/setup.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#!/usr/bin/env python

#-------------------------------------------------------------------------
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
# --------------------------------------------------------------------------

import re
import os.path
Expand All @@ -18,50 +18,49 @@
package_folder_path = "azure/core/experimental"

# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', # type: ignore
fd.read(), re.MULTILINE).group(1)
with open(os.path.join(package_folder_path, "_version.py"), "r") as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) # type: ignore

if not version:
raise RuntimeError('Cannot find version information')
raise RuntimeError("Cannot find version information")

with open('README.md', encoding='utf-8') as f:
with open("README.md", encoding="utf-8") as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
with open("CHANGELOG.md", encoding="utf-8") as f:
changelog = f.read()

setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + '\n\n' + changelog,
long_description_content_type='text/markdown',
license='MIT License',
author='Microsoft Corporation',
author_email='[email protected]',
url='https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core-experimental',
description="Microsoft Azure {} Library for Python".format(PACKAGE_PPRINT_NAME),
long_description=readme + "\n\n" + changelog,
long_description_content_type="text/markdown",
license="MIT License",
author="Microsoft Corporation",
author_email="[email protected]",
url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/core/azure-core-experimental",
classifiers=[
"Development Status :: 4 - Beta",
'Programming Language :: Python',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'License :: OSI Approved :: MIT License',
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"License :: OSI Approved :: MIT License",
],
zip_safe=False,
packages=[
'azure.core.experimental',
"azure.core.experimental",
],
include_package_data=True,
package_data={
'pytyped': ['py.typed'],
"pytyped": ["py.typed"],
},
python_requires=">=3.7",
install_requires=[
'azure-core<2.0.0,>=1.25.0',
"azure-core<2.0.0,>=1.25.0",
],
)
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ 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:
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
Expand All @@ -106,9 +104,7 @@ async def test_successful_send(self, mock_pyfetch, mock_pyodide_module, pipeline
method = "POST"
headers = {"key": "value"}
data = b"data"
request = HttpRequest(
method=method, url=PLACEHOLDER_ENDPOINT, headers=headers, data=data
)
request = HttpRequest(method=method, url=PLACEHOLDER_ENDPOINT, headers=headers, data=data)
response_body = b"0123"
response_headers = {"header": "value"}
response_status = 200
Expand Down Expand Up @@ -167,4 +163,5 @@ def test_valid_import(self, transport):
"""
# Use patch so we don't clutter up the `sys.modules` namespace.
import azure.core.experimental.transport as transport

assert transport.PyodideTransport
2 changes: 1 addition & 1 deletion sdk/core/azure-core-tracing-opencensus/azure/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from typing import Dict, Optional, Union, Callable, Sequence, Any

from azure.core.pipeline.transport import HttpRequest, HttpResponse

AttributeValue = Union[
str,
bool,
Expand All @@ -40,7 +41,7 @@

__version__ = VERSION

_config_integration.trace_integrations(['threading'])
_config_integration.trace_integrations(["threading"])


class OpenCensusSpan(HttpSpanMixin, object):
Expand All @@ -61,20 +62,26 @@ def __init__(self, span=None, name="span", **kwargs):
:paramtype links: list[~azure.core.tracing.Link]
"""
tracer = self.get_current_tracer()
value = kwargs.pop('kind', None)
value = kwargs.pop("kind", None)
kind = (
OpenCensusSpanKind.CLIENT if value == SpanKind.CLIENT else
OpenCensusSpanKind.CLIENT if value == SpanKind.PRODUCER else # No producer in opencensus
OpenCensusSpanKind.SERVER if value == SpanKind.SERVER else
OpenCensusSpanKind.CLIENT if value == SpanKind.CONSUMER else # No consumer in opencensus
OpenCensusSpanKind.UNSPECIFIED if value == SpanKind.INTERNAL else # No internal in opencensus
OpenCensusSpanKind.UNSPECIFIED if value == SpanKind.UNSPECIFIED else
None
) # type: SpanKind
OpenCensusSpanKind.CLIENT
if value == SpanKind.CLIENT
else OpenCensusSpanKind.CLIENT
if value == SpanKind.PRODUCER
else OpenCensusSpanKind.SERVER # No producer in opencensus
if value == SpanKind.SERVER
else OpenCensusSpanKind.CLIENT
if value == SpanKind.CONSUMER
else OpenCensusSpanKind.UNSPECIFIED # No consumer in opencensus
if value == SpanKind.INTERNAL
else OpenCensusSpanKind.UNSPECIFIED # No internal in opencensus
if value == SpanKind.UNSPECIFIED
else None
) # type: SpanKind
if value and kind is None:
raise ValueError("Kind {} is not supported in OpenCensus".format(value))

links = kwargs.pop('links', None)
links = kwargs.pop("links", None)
self._span_instance = span or tracer.start_span(name=name, **kwargs)
if kind is not None:
self._span_instance.span_kind = kind
Expand All @@ -84,11 +91,8 @@ def __init__(self, span=None, name="span", **kwargs):
for link in links:
ctx = trace_context_http_header_format.TraceContextPropagator().from_headers(link.headers)
self._span_instance.add_link(
Link(
trace_id=ctx.trace_id,
span_id=ctx.span_id,
attributes=link.attributes
))
Link(trace_id=ctx.trace_id, span_id=ctx.span_id, attributes=link.attributes)
)
except AttributeError:
# we will just send the links as is if it's not ~azure.core.tracing.Link without any validation
# assuming user knows what they are doing.
Expand Down Expand Up @@ -121,10 +125,13 @@ def kind(self):
"""Get the span kind of this span."""
value = self.span_instance.span_kind
return (
SpanKind.CLIENT if value == OpenCensusSpanKind.CLIENT else
SpanKind.SERVER if value == OpenCensusSpanKind.SERVER else
SpanKind.UNSPECIFIED if value == OpenCensusSpanKind.UNSPECIFIED else
None
SpanKind.CLIENT
if value == OpenCensusSpanKind.CLIENT
else SpanKind.SERVER
if value == OpenCensusSpanKind.SERVER
else SpanKind.UNSPECIFIED
if value == OpenCensusSpanKind.UNSPECIFIED
else None
)

_KIND_MAPPING = {
Expand Down Expand Up @@ -171,7 +178,7 @@ def to_header(self):
:return: A key value pair dictionary
"""
tracer_from_context = self.get_current_tracer()
temp_headers = {} # type: Dict[str, str]
temp_headers = {} # type: Dict[str, str]
if tracer_from_context is not None:
ctx = tracer_from_context.span_context
try:
Expand Down Expand Up @@ -205,7 +212,7 @@ def get_trace_parent(self):
:return: a traceparent string
:rtype: str
"""
return self.to_header()['traceparent']
return self.to_header()["traceparent"]

@classmethod
def link(cls, traceparent, attributes=None):
Expand All @@ -216,9 +223,7 @@ def link(cls, traceparent, attributes=None):
:param traceparent: A complete traceparent
:type traceparent: str
"""
cls.link_from_headers({
'traceparent': traceparent
}, attributes)
cls.link_from_headers({"traceparent": traceparent}, attributes)

@classmethod
def link_from_headers(cls, headers, attributes=None):
Expand All @@ -231,11 +236,7 @@ def link_from_headers(cls, headers, attributes=None):
"""
ctx = trace_context_http_header_format.TraceContextPropagator().from_headers(headers)
current_span = cls.get_current_span()
current_span.add_link(Link(
trace_id=ctx.trace_id,
span_id=ctx.span_id,
attributes=attributes
))
current_span.add_link(Link(trace_id=ctx.trace_id, span_id=ctx.span_id, attributes=attributes))

@classmethod
def get_current_span(cls):
Expand Down Expand Up @@ -268,8 +269,7 @@ def set_current_span(cls, span):
@classmethod
def change_context(cls, span):
# type: (Span) -> ContextManager
"""Change the context for the life of this context manager.
"""
"""Change the context for the life of this context manager."""
original_span = cls.get_current_span()
try:
execution_context.set_current_span(span)
Expand Down
Loading