Skip to content

Commit

Permalink
azure_cloud_setting (#30825)
Browse files Browse the repository at this point in the history
* azure_cloud_setting

* update

* update

* update

* update

* update

* update

* update test

* update

* updates

* update

* Update changelog
  • Loading branch information
xiangyan99 authored Aug 14, 2024
1 parent 0572be4 commit e27d899
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 4 deletions.
1 change: 1 addition & 0 deletions sdk/core/azure-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- `AccessToken` now has an optional `refresh_on` attribute that can be used to specify when the token should be refreshed. #36183
- `BearerTokenCredentialPolicy` and `AsyncBearerTokenCredentialPolicy` now check the `refresh_on` attribute when determining if a token request should be made.
- Added `azure.core.AzureClouds` enum to represent the different Azure clouds.

### Breaking Changes

Expand Down
2 changes: 2 additions & 0 deletions sdk/core/azure-core/azure/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

from ._pipeline_client import PipelineClient
from ._match_conditions import MatchConditions
from ._azure_clouds import AzureClouds
from ._enum_meta import CaseInsensitiveEnumMeta
from ._pipeline_client_async import AsyncPipelineClient

Expand All @@ -38,4 +39,5 @@
"MatchConditions",
"CaseInsensitiveEnumMeta",
"AsyncPipelineClient",
"AzureClouds",
]
41 changes: 41 additions & 0 deletions sdk/core/azure-core/azure/core/_azure_clouds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# --------------------------------------------------------------------------
#
# 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.
#
# --------------------------------------------------------------------------
# pylint: disable=enum-must-inherit-case-insensitive-enum-meta

from enum import Enum


class AzureClouds(str, Enum):
"""An enum to describe Azure Cloud."""

AZURE_PUBLIC_CLOUD = "AZURE_PUBLIC_CLOUD"
"""Azure public cloud"""

AZURE_CHINA_CLOUD = "AZURE_CHINA_CLOUD"
"""Azure China cloud"""

AZURE_US_GOVERNMENT = "AZURE_US_GOVERNMENT"
"""Azure US government cloud"""
30 changes: 30 additions & 0 deletions sdk/core/azure-core/azure/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import sys
from typing import Type, Optional, Callable, Union, Dict, Any, TypeVar, Tuple, Generic, Mapping, List
from azure.core.tracing import AbstractSpan
from ._azure_clouds import AzureClouds

ValidInputType = TypeVar("ValidInputType")
ValueType = TypeVar("ValueType")
Expand Down Expand Up @@ -114,6 +115,28 @@ def convert_logging(value: Union[str, int]) -> int:
return level


def convert_azure_cloud(value: Union[str, AzureClouds]) -> AzureClouds:
"""Convert a string to an Azure Cloud
:param value: the value to convert
:type value: string
:returns: An AzureClouds enum value
:rtype: AzureClouds
:raises ValueError: If conversion to AzureClouds fails
"""
if isinstance(value, AzureClouds):
return value
if isinstance(value, str):
azure_clouds = {cloud.name: cloud for cloud in AzureClouds}
if value in azure_clouds:
return azure_clouds[value]
raise ValueError(
"Cannot convert {} to Azure Cloud, valid values are: {}".format(value, ", ".join(azure_clouds.keys()))
)
raise ValueError("Cannot convert {} to Azure Cloud".format(value))


def _get_opencensus_span() -> Optional[Type[AbstractSpan]]:
"""Returns the OpenCensusSpan if the opencensus tracing plugin is installed else returns None.
Expand Down Expand Up @@ -482,6 +505,13 @@ def _config(self, props: Mapping[str, Any]) -> Tuple[Any, ...]:
default=None,
)

azure_cloud: PrioritizedSetting[Union[str, AzureClouds], AzureClouds] = PrioritizedSetting(
"azure_cloud",
env_var="AZURE_CLOUD",
convert=convert_azure_cloud,
default=AzureClouds.AZURE_PUBLIC_CLOUD,
)


settings: Settings = Settings()
"""The settings unique instance.
Expand Down
26 changes: 22 additions & 4 deletions sdk/core/azure-core/tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

# module under test
import azure.core.settings as m
from azure.core import AzureClouds


class TestPrioritizedSetting(object):
Expand Down Expand Up @@ -167,6 +168,10 @@ def test_convert_logging_bad(self):
with pytest.raises(ValueError):
m.convert_logging("junk")

def test_convert_azure_cloud(self):
with pytest.raises(ValueError):
m.convert_azure_cloud(10)


_standard_settings = ["log_level", "tracing_enabled"]

Expand All @@ -184,40 +189,53 @@ def test_setting_env_var(self, name):
assert ps.env_var == "AZURE_" + name.upper()

def test_init(self):
assert m.settings.defaults_only == False
assert m.settings.defaults_only is False

def test_config(self):
val = m.settings.config(log_level=30, tracing_enabled=True)
assert isinstance(val, tuple)
assert val.tracing_enabled == True
assert val.tracing_enabled is True
assert val.log_level == 30
os.environ["AZURE_LOG_LEVEL"] = "debug"
val = m.settings.config(tracing_enabled=False)
assert val.tracing_enabled == False
assert val.tracing_enabled is False
assert val.log_level == 10

val = m.settings.config(log_level=30, tracing_enabled=False)
assert val.tracing_enabled == False
assert val.tracing_enabled is False
assert val.log_level == 30
del os.environ["AZURE_LOG_LEVEL"]

val = m.settings.config(azure_cloud=AzureClouds.AZURE_US_GOVERNMENT)
assert val.azure_cloud == AzureClouds.AZURE_US_GOVERNMENT

def test_defaults(self):
val = m.settings.defaults
# assert isinstance(val, tuple)
defaults = m.settings.config(log_level=20, tracing_enabled=False, tracing_implementation=None)
assert val.log_level == defaults.log_level
assert val.tracing_enabled == defaults.tracing_enabled
assert val.tracing_implementation == defaults.tracing_implementation
assert val.azure_cloud == AzureClouds.AZURE_PUBLIC_CLOUD
os.environ["AZURE_LOG_LEVEL"] = "debug"
defaults = m.settings.config(log_level=20, tracing_enabled=False, tracing_implementation=None)
assert val.log_level == defaults.log_level
assert val.tracing_enabled == defaults.tracing_enabled
assert val.tracing_implementation == defaults.tracing_implementation
del os.environ["AZURE_LOG_LEVEL"]
os.environ["AZURE_CLOUD"] = "AZURE_PUBLIC_CLOUD"
defaults = m.settings.config(log_level=20, tracing_enabled=False, tracing_implementation=None)
assert val.azure_cloud == AzureClouds.AZURE_PUBLIC_CLOUD
del os.environ["AZURE_CLOUD"]

def test_current(self):
os.environ["AZURE_LOG_LEVEL"] = "debug"
val = m.settings.current
assert isinstance(val, tuple)
assert val.log_level == 10
del os.environ["AZURE_LOG_LEVEL"]
os.environ["AZURE_CLOUD"] = "AZURE_CHINA_CLOUD"
val = m.settings.current
assert isinstance(val, tuple)
assert val.azure_cloud == AzureClouds.AZURE_CHINA_CLOUD
del os.environ["AZURE_CLOUD"]

0 comments on commit e27d899

Please sign in to comment.